हिंदी
तमिलनाडु बोर्ड ऑफ सेकेंडरी एज्युकेशनएचएससी विज्ञान कक्षा ११

Explain the scope of variables with examples.

Advertisements
Advertisements

प्रश्न

Explain the scope of variables with examples.

संक्षेप में उत्तर
Advertisements

उत्तर

Scope refers to the accessibility of a variable.
There are four types of scopes in C++

  1. Local Scope
  2. Function Scope
  3. File Scope
  4. Class Scope

1. Local Scope:

  • A local variable is defined within a block. A block of code begins and ends with curly braces {}.
  • The scope of a local variable is the block in which it is defined.
  • A local variable cannot be accessed from outside the block of its declaration.
  • A local variable is created upon entry into its block and destroyed upon exit;

Example:
int main( )
{
int a,b; //Local variable
}

2. Function Scope:

  • The scope of a variable within a function is extended to the function block and all sub-blocks therein.
  • The lifetime of a function scope variable is the lifetime of the function block.

Example:
int. sum(int x, int y); //x and y has function scope.

3. File Scope:

  • A variable declared above all blocks and functions (including main()) has the scope of a file.
  • The lifetime of a file scope variable is the lifetime of a program.
  • The file scope variable is also called a global variable.

Example:
#include
using namespace std;
int x,y; //x and y are global variable
void main()
{
……..
}

4. Class Scope:

  • Data members declared in a class have the class scope.
  • Data members declared in a class can be accessed by all member functions of the class.

Example:
Class example
{
int x,y; //x and y can be accessed by print() and void():
void print();
Void total();
};

Class Scope:

A class is a new way of creating and implementing a user-defined data type. Classes provide a method for packing together data of different types.
Data members are the data variables that represent the features or properties of a class.

class student
}
private:
int mark1, mark2, total;
};
The class student contains mark1, mark2, and total are data variables. Its scope is within the class of students only. 
shaalaa.com
Scope Rules of Variables - Local and Global Variables
  क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
अध्याय 11: Functions - Evaluation - Section - D [पृष्ठ २०५]

APPEARS IN

सामाचीर कलवी Computer Science [English] Class 11 TN Board
अध्याय 11 Functions
Evaluation - Section - D | Q 4. | पृष्ठ २०५
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×