My C++ teacher said global variables are bad practice?

Apr 27, 2010 at 8:32pm
Why is this, they seem to be the easiest way to get what I need to get done - done.
Apr 27, 2010 at 8:40pm
Filling the global scope with variables is easy but there are some reason it is bad practice.
Some are:
- you can't have global variables with the same name on different files unless they are static or in an unnamed namespace
- a function using globals is not reentrant
- it may lead to confusion with local variables
- two functions may modify the same variable producing unexpected results
You can usually replace globals with some function parameters
Last edited on Apr 27, 2010 at 8:42pm
Apr 27, 2010 at 10:27pm
They may be the easiest, but think about modular programing. Modular programing means building a program by modules which interact (think of them like some big chunks of code with specific roles).

Every module should be independent from the others so it can be reused in other projects (global variables "tie" your module to a specific implementation). Also different modules are created by different people (or teams) so global variables only get in the way, as you can imagine.

Think about reusing a function in another program. If you use a global variable in that function, then you have to recreate that global in the new program or else the function will simply not work.
Apr 27, 2010 at 11:56pm
Ok cool thanks for the replies.
Apr 28, 2010 at 6:14am
- two functions may modify the same variable



After i had this problem for a while - i gave myself a new rule:

"Only use Global Variables as the very last resort to a fix."
Topic archived. No new replies allowed.