A variable that is declared inside a function is called local variable. While, a variable that is declared outside of the main() function is called global variable.
The following is the main difference between local and global variable.
|Local Variable||Global Variable|
|It’s declared inside the main() function or any other user defined function.||It’s declared outside the main() function or any other user defined function.|
|It can only be used or accessed in the function in which this is declared.||It can be used or accessed in any part or function of the program.|
|It is created into memory when control enters into the function or block in which it is declared. In the same way, this type of variable destroyed from the memory when control exist the function or block.||Generally, It is created into memory when the program execution begins. Such kind of variables are destroyed when the program execution is terminated.|
|The values of local variables can’t be shared among other functions.||The values of global variables can be shared among other functions.|
|The use of local variables is recommended during program designing.||The use of global variables should be limited during program designing.|
Scope and Lifetime of Local Variable
A portion of a program where a variable can be accessed is called scope. A local variable can be accessed only in the function in which it is declared.
The time period for which a variable exist in memory is called lifetime of a variable. The lifetime of the local variable starts when it is created in the memory and ends when it’s destroyed from the memory. When the same function is called again for execution, local variables are created again.
Note: A variable can be used only during its lifetime.
Scope and Lifetime of Global Variable
A global variable can be used by all functions in the program. It means that global variable can be accessed from any part of the program at any time. It has file scope.
The global variables exist in the memory throughout the program execution. The lifetime of global variables is the time between the starting and termination of a program execution.