# Difference Between Local and Global Variable

In this post, we will understand the difference between local and global variables.

## Local variable

• It is generally declared inside a function.

• If it isn’t initialized, a garbage value is stored inside it.

• It is created when the function begins its execution.

• It is lost when the function is terminated.

• Data sharing is not possible since the local variable/data can be accessed by a single function.

• Parameters need to be passed to local variables so that they can access the value in the function.

• It is stored on a stack, unless mentioned otherwise.

• They can be accessed using statement inside the function where they are declared.

• When the changes are made to local variable in a function, the changes are not reflected in the other function.

• Local variables can be accessed with the help of statements, inside a function in which they are declared.

## Example

Following is an example −

#include <stdio.h>
int main () {
/* local variable declaration */
int a, b;
int c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d", a, b, c);
return 0;
}

## Global variable

• It is declared outside the function.

• If it isn’t initialized, the value of zero is stored in it as default.

• It is created before the global execution of the program.

• It is lost when the program terminates.

• Data sharing is possible since multiple functions can access the global variable.

• They are visible throughout the program, hence passing parameters is not required.

• It can be accessed using any statement within the program.

• It is stored on a specific location inside the program, which is decided by the compiler.

• When changes are made to the global variable in one function, these changes are reflected in the other parts of the program as well.

## Example

Following is an example −

#include
/* global variable declaration */
int g;
int main () {
/* local variable declaration */
int a, b;
/* actual initialization */
a = 10;
b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d", a, b, g);
return 0;
}