Global variables are globally accessible,and their definition is retained to be short because all functions can change them during runtime which may cause errors. After declaration, global variables reside in the memory throughout the program runtime; sometimes this may create memory space deficiency. A variable that has a global scope will be available technically starting from the point of its definition till the end of program code. There are certain benefits of using global variables:
Programmers have to declare global variables only once outside the main function within a program.
Global variables can be accessed by all the functions or sub-routines in a source code.
When multiple functions wants to access the same data, global variables can work effectively.
Global variables are stored on a static location provided by the compiler and preferably used for storing constants.
Global Variable vs Local Variable
Declared outside the function Declared inside the function.
These can be accessed by any function or module within a program. These can be accessed only inside a function they are declared in by statements.
A global variable provides data sharing as same data can be accessed by multiple functions. Local variables can be accessed by only single function, so it is not possible to share data.
Zero is stored by default if global variables are not initialized. Some garbage value is stored if local variables are not initialized.
Variations are visible in whole program if the value of global variable is updated. If any value of local variable is altered, the modifications are not visible to other functions.
Lifetime of global variable starts when itâ€™s declared till the program terminates. Local variables are declared while executing a function and it is lost when function ends.
The local and global variables are similarly significant while developing a program in any programming language. In any case,an enormous number of the global variable may takes a tremendous memory that can cause memory shortage. An unwanted change to global variables will be hard to recognize. Therefore, it is always suggested to avoid declaring adverse global variables.
Disadvantages of Global Variable
Every so often a large number of variables are declared as global in a program and consume memory for storage; this usually causes Out of Memory issue.
Functions can modify the value of global variable which will result in unpredictable errors and programmers might have to re-check the whole program.
All modules or sub-routines need to be changed in which global variables are called; if the whole program is restructured.