Tamil Nadu Board of Secondary EducationHSC Science Class 11th

Explain the scope of variables with examples. - Computer Science

Advertisement Remove all ads
Advertisement Remove all ads
Advertisement Remove all ads
Answer in Brief

Explain the scope of variables with examples.

Advertisement Remove all ads


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;

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.

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.

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.

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
int mark1, mark2, total;
The class student contains mark1, mark2, and total are data variables. Its scope is within the class of students only. 
Concept: Scope Rules of Variables - Local and Global Variables
  Is there an error in this question or solution?
Chapter 11: Functions - Evaluation - Section - D [Page 205]


Tamil Nadu Board Samacheer Kalvi Class 11th Computer Science Answers Guide
Chapter 11 Functions
Evaluation - Section - D | Q 4. | Page 205

View all notifications

      Forgot password?
View in app×