A global variables are declared outside all functions, usually at the top of the program.
- Global variables have a program-wide scope which means can be accessed and modified by any function in the program. Note that local variables are restricted to a single function.
- If not explicitly initialized, global variables are automatically set to 0.
- They exist in memory for the entire runtime of the program.
#include <stdio.h>
// global variables
int a, b;
void add()
{
// we are adding values of global a and b i.e. 10+15
printf("%d", a + b);
}
int main()
{
// we are now updating the values of global variables as you can see we dont need to redeclare a and b
// again
a = 10;
b = 15;
add();
return 0;
}
Output
25
Advantages of Global Variable
- Global variables can be accessed by all the functions present in the program.
- Only a one-time declaration is required.
- Global variables are very useful if all the functions are accessing the same data.
Disadvantages of Global Variable
- The value of a global variable can be changed accidentally as it can be used by any function in the program.
- If we use a large number of global variables, then there is a high chance of error generation in the program.
- It is generally recommended to avoid global variables unless necessary.