Global Variable

Local Variable

Can be used anywhere globally inside the program Variables that are declared within or inside a function block are known as Local variables
Global Variables are the variables that are initialized outside the functions or block

 

These variables can only be accessed within the function in which they are declared.

 

Can be accessed by any function present in the program The lifetime of the local variable is within its function only, which means the variable exists till the function executes.

 

Once the global variable is declared the value of the global variable can be changed with different functions Once function execution is completed, local variables are destroyed and no longer exist outside the function.

 

Life time of the global variable is till the program executes The reason for the limited scope of local variables is that local variables are stored in the stack, which is dynamic in nature and automatically cleans up the data stored within it.

 

These variables are stored in fixed memory locations given by the computer

 

But by making the variable static with “static” keyword, we can retain the value of local variable
Global variables are useful for cases where all functions need to access the same data. If it is not initialized, a garbage value is stored inside it.

Categorized in: