C local block scope of variable

Block Scope of Variable :

Block Scope i.e Local Scope of variable is used to evaluate expression at block level. Variable is said to have local scope / block scope if it is defined within function or local block.In short we can say that local variables are in block scope.

Important Points About Block Scope :

  1. Block Scope is also called Local Scope
  2. It can be used only within a function or a block
  3. It is not visible outside the block
  4. Variables defined within local scope is called as Local variables

 Live Example : Block/Local Scope


void message();

void main()
int num1 = 0 ;     // Local to main

void message()
int num1 = 1 ;         // Local to Function message 


0 1

Explanation Of Code :

  1. In both the functions main() and message() we have declared same variable.Since these two functions are having different block/local scope, compiler will not throw compile error.
  2. Whenever our control is in main() function we have access to variable from main() function only. Thus 0 will be printed inside main() function.
  3. As soon as control goes inside message() function , Local copy of main is no longer accessible. Since we have re-declared same variable inside message() function, we can access variable local to message(). “1” will be printed on the screen.