Variable scope is an area of a program where variables can be accessed.
Two types of variables depending on a variable scope.
- local scope variable aka. local variable
- global scope variable aka. global variables
Local variables
- The variable declared within parentheses of function or a block is called a local variable.
- These local variables are stored in stack section in memory.
- The scope and lifetime of a local variable are within the block/function.
- The default/initial value of a local variable is garbage.
- A local variable has higher priority than a global variable.
1 2 3 4 5 6 7 8 9 10 11 |
#include<stdio.h> int main () { int x,y,z; //local variables x = 5; y = 2; z = x + y; printf ("value of z = %d\n", z); } |
Output:
1 |
value of z = 7 |
Global variables
The variables declare above the main() function are called as global variables
These global variables are stored in the data section of memory.
The scope and lifetime of a global variable are throughout the program.
The default/initial value of a global variable is zero.
The global variable should be initialized at the time of declaration.
1 2 3 4 5 6 7 8 9 10 11 12 |
#include<stdio.h> int z; //global variable int main ( ) { int x,y; //local variables x = 5; y = 2; z = x + y; printf ("value of z = %d\n", z); } |
Output:
1 |
value of z = 7 |
Some more examples –
- A local variable has higher priority than a global variable.
123456int a = 10;int main( ){int a = 100;printf("a = %d ", a);}
Output
1a = 100 - Constant local variable should be initialized at time of declaration.
123456int main( ){const int a;a = 10; //errorprintf(" %d ", a);} - The global variable should be initialized at the time of declaration.
123456int a;a = 10; //not allowedint main(){printf(" %d ", a);}