Following are the differences between a local variable and global variable:
Basis for comparison Local variable Global variable
Declaration A variable which is declared inside function or block is known as a local variable. A variable which is declared outside function or block is known as a global variable.
Scope The scope of a variable is available within a function in which they are declared. The scope of a variable is available throughout the program.
Access Variables can be accessed only by those statements inside a function in which they are declared. Any statement in the entire program can access variables.
Life Life of a variable is created when the function block is entered and destroyed on its exit. Life of a variable exists until the program is executing.
Storage Variables are stored in a stack unless specified. The compiler decides the storage location of a variable.
Local variables are created when the function starts its execution and are lost when the function ends.
Global variables, on the other hand, are created as execution of the program begins and are lost when the program is ended. In contrast to global variables, local variables do not offer data sharing.
