Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
2.4k views
in Functions by (49.1k points)
closed by

Explain scope of variable with example.

1 Answer

+1 vote
by (54.8k points)
selected by
 
Best answer

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 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(intx, 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 as 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 has 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();

};

Related questions

0 votes
1 answer
asked Jan 11, 2021 in Functions by Padma01 (49.1k points)
0 votes
1 answer
asked Jan 11, 2021 in Functions by Padma01 (49.1k points)
0 votes
1 answer
asked Jan 11, 2021 in Functions by Padma01 (49.1k points)
0 votes
1 answer

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

...