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 :
- Block Scope is also called Local Scope
- It can be used only within a function or a block
- It is not visible outside the block
- Variables defined within local scope is called as Local variables
Live Example : Block/Local Scope
#include<stdio.h> void message(); void main() { int num1 = 0 ; // Local to main printf("%d",num1); message(); } void message() { int num1 = 1 ; // Local to Function message printf("%d",num1); }
Output:
0 1
Explanation Of Code :
- 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.
- Whenever our control is in main() function we have access to variable from main() function only. Thus 0 will be printed inside main() function.
- 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.