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

Why is this, they seem to be the easiest way to get what I need to get done - done.
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
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.
Ok cool thanks for the replies.
- 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.