Five reasons why not to use global variables?
Global variables are those variables which can be accessed and modified by any module. They are declared in outermost scope so that they are visible to every inner scope module.
They are usually considered a bad practice because of their non-locality. They create mutual dependencies and increase the complexity of the program. However, there are some places where global variables are suitable to use. When one wants to avoid frequent passing of parameters forms one function to another, global variables can be of use. They are used to pass information between modules that do not share called / caller relationships such as concurrent threads and signal handlers or interrupt routines.
Why they should be avoided when unnecessary?
As explained in the introduction section, global variables induce interdependency between modules thus increasing the complexity of the code making it hard to analyze it. Here I give you other reason for not to use a global variable unless absolutely necessary.
Global variables are declared in the outermost scope. So if a function uses it in the innermost scope we have to keep track that whether that variable has been modified before that is been used in the function. Functions are easy to analyze when their variables are localized and have a minimum influence of other modules over them. If you code is large enough, then another problem called thrashing (related to paging in OS) may occur (only if there is no spare memory left) while executing your code as the variable and code may be on different pages.
Coupling between modules of the code should be as low as possible in order to make it maintainable in the future. When you use global variables in code, they induce coupling between modules.
This case arises when your application is multithreaded. If more than one threads try to access the same variable at the same time, which might result in deadlock situations. Special precaution should be taken to avoid such situation resulting in extra code. We have to implement lock and unlock functions to ensure single thread access to the global variable. There may be a possibility that threads get obsolete values.
No access control or constraint checking
Global variables can be get or set in any part of the program without worrying about the rules to access them as there are no rules. This greatly hinders security when you are using third party tools.
Difficult to test
Code which use global variables are difficult to test as there is no easy method to set a clean environment between run. It will be very difficult to test modules in isolation as Unit test suggests. There will be some implicit effect of other modules on the module in form of global variables, so it will be difficult to pin point and debug code.
These are five reasons why you should avoid global variables as far as possible.