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 as bad practice because of their non locality.They create mutual dependencies and increase complexity of program.However, there are some places where global variables are suitable to use.When one wants to avoid frequent passing of parameters form one function to another, global variables can be of use. They are used to pass information
between modules that do not share called / caller relationship 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 complexity of the code making it hard to analyze it.Here I give you other reason for not to use global variable unless absolutely necessary.
Reason 1: Non locality
Global variables are declared in the outmost scope. So if a function uses it in the innermost scope we have to keep track that whether that variable have been modified before that is been used in the function. Functions are easy to analyze when their variables are localized and have 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.
Reason 2: Implicit coupling
Coupling between modules of the code should be as low as possible in order to make it maintainable in future. When you use global variables in code,they induce coupling between modules.
Reason 3: Concurrency issues
This case arises when your application is multithreaded. If more than one thread 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.
Reason 4: 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.
Reason 5: 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.