Header Responsive Ads

Variable Scope

In programming, scope of variable means the boundary of code within which the variable can be accessed. It is the visibility of variable. There are three types of variable scopes

  • Block level scope
  • Function level scope
  • Global scope

Block Level Scope

A variable declared inside curly bracket { } of if statement, if-else statement, switch statement, while loop, do-while loop and for loop has block level scope. Such variable can only be accessed within block. It is not visible outside the block.

Function level scope

A variable declared in the body of function has function level scope. Such variable can be accessed anywhere in that function. However it cannot be accessed outside that function or in another function.

Global scope

A variable declared outside main function has global scope. Such variables can be accessed anywhere in the program. All global variables can be kept in a separate header file and include that header file in main source file.

Below is an example to demonstrate all three variable scopes

variable scope in c
Variable scope in C/C++

In above example, all three scopes of variable is highlighted with different colors as

  • Green rectangle is boundary of block level scope.
  • Red rectangle is boundary of function level scope.
  • Blue rectangle is boundary of global scope.

Variable named blockScopeVariable declared inside block can only be accessed within the block and cannot be accessed outside the block. You can see that blockScopeVariable is accessible inside green rectangle but not in red and blue rectangles.

Variable named functionScopeVariable declared in function scope can be accessed anywhere within the function but not outside the function or in other functions. You can see that functionScopeVariable is accessible in green and red rectangle and not in blue rectangle.

Variable named globalVariable declared in global scope can be accessed anywhere in the program. You can see that globalVariable is accessible in green, red and blue rectangle.

Post a Comment

Previous Post Next Post

In Article Ads 1 Before Post

In Article Ads 2 After Post