A global variable is a variable that is declared outside all functions. Global variables hold their values throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program.
A global variable can be accessed by any function . That is, a global variable is available for use throughout your entire program after its declaration.
9
Here, 'a'
and 'b'
are global variables. Because they are declared out side of the function
12
As you can see two global variables are declared, A
and B
. These variables can be used in main()
and Add()
. The local variable answer can only be used in main()
.
Parameter | Local | Global |
---|---|---|
Scope | It is declared inside a function. | It is declared outside the function. |
Value | If it is not initialized, a garbage value is stored | If it is not initialized zero is stored as default. |
Lifetime | It is created when the function starts execution and lost when the functions terminate. | It is created before the program's global execution starts and lost when the program terminates. |
Data sharing | Data sharing is not possible as data of the local variable can be accessed by only one function. | Data sharing is possible as multiple functions can access the same global variable. |
Parameters | Parameters passing is required for local variables to access the value in other function | Parameters passing is not necessary for a global variable as it is visible throughout the program |
Modification of variable value | When the value of the local variable is modified in one function, the changes are not visible in another function. | When the value of the global variable is modified in one function changes are visible in the rest of the program. |
Accessed by | Local variables can be accessed with the help of statements, inside a function in which they are declared. | You can access global variables by any statement in the program. |
Memory storage | It is stored on the stack unless specified. | It is stored on a fixed location decided by the compiler. |