The following image briefly explains the significant differences between local & global variables in C.
Local variable | Global variable |
---|---|
1. Variables declared inside the function. | 1. Variables declared outside the function. |
2. Scope is throughout the block. | 2. Scope is throughout the program. |
3. Memory allocated in the stack frame of the function in which it is declared and it is valid till function finishes the execution. | 3. Memory allocated in the .data section of a program and it is valid till the program finishes execution. |
4. Can only be accessed from inside the block in which we declared it. | 4. Can be accessed by all the functions in the program. |
Local variable example
#include <stdio.h>
int main()
{
fun();
return 0;
}
int fun()
{
// local variables
int a = 20;
int b = 30;
int c = 40;
}
Global variable example
#include <stdio.h>
// global variable
int a = 10;
void main()
{
printf("Printing in main %d", a);
}