Fundamental differences between Local and Global variables:
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. |