A variable is a memory location inside memory which is referred using a name. The value inside a variable changes throughout the execution of the program. Based on where the variable is declared in the program, variables can be divided into two types. They are:
- Local Variables
- Global Variables
A variable is said to be a local variable if it is declared inside a function or inside a block. The scope of the local variable is within the function or block in which it was declared. A local variable remains in memory until the execution of the function or block in which it was declared in completes. Let’s see the following example:
In the above example, the variable x is a local variable with respect to the main function. Variable x is not accessible outside main function and x remains in the memory until the execution of the main function completes.
A variable is said to be a global variable if it is declared outside all the functions in the program. A global variable can be accessed throughout the program by any function. A global variable remains in the memory until the program terminates. In a multi-file program, a global can be accessed in other files wherever the variable is declared with the storage class extern.
Types of variables and their scope and lifetime can be summarized as shown below:
C program to demonstrate local and global variables:
int g = 10;
int x = 20;
printf("Inside main, g = %d",g);
printf("\nInside main, x = %d",x);
int y = 30;
printf("\nInside block, g = %d",g);
printf("\nInside block, y = %d",y);
printf("\nInside block, x = %d",x);
printf("\nOutside block, g = %d",g);
/*printf("Outside block, y = %d",y);*/
printf("\nOutside block, x = %d",x);
In the above example, g is a global variable and x is a local variable with respect to main and y is a local variable within the block. The variable y cannot be accessed outside the block. That is why the printf statement outside the block accessing the value of the variable y has been commented out.