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.
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.