There are a number of reasons to avoid global variables. Here are a few.
1. Variables in the global namespace make it hard for two programmers to work on the same project. One programmer might use a global variable for one thing in his/her code and another use it for something else. This makes problems hard to track down because two people wrote pieces of code that work, but the system as a whole does not.
2. Global variables are always consume memory, even when not in use. When variables are declared in functions (on the stack) or through memory allocation (on the heap) the space they use can be freed up when they are no longer needed (by deallocation, garbage collection, or stack “popping”.) A global variable's memory cannot be freed until the program closes.
3. Global variables make multi-threaded programming harder. Many programs, these days, are multi-threaded to take advantage of multi-core processors and other OS parallelization mechanisms. When you have a global variable that is accessed by two or more threads you must perform expensive (and sometimes complicated) locking to prevent the threads from interfering with each other. Of course, by the time you are skilled enough to write multi-threaded applications, you will have stopped needing global variables because your mental toolkit of data communication will include a lot of better design patterns.
One thing you should be aware of is the difference between global “variables” and static (kind of like global) constants. Static constants are perfectly ok in most cases. Since they don’t change, none of the three reasons I listed to avoid global variables apply. A smart complier will put those constants in a special place in memory that will allow the OS to make them faster and protect them from malice. Since these constants do not change you don’t want to pass them around your program because making copies on the stack or in the heap is wasteful.
This is a good question that I wish beginner programmers would ask more often. There are a sad number of intermediate programmers out there with bad habits because their teachers never gave them good reasons to avoid picking up these habits. The teacher just said “don’t do it, you will regret it” and the beginner thinks “but if I can save typing and planning overhead why should I follow some arbitrary rule.”