Why should we avoid using global variables in C/C++?

We should avoid using global variables in any language, not only C++. This is because these variables pollute the global namespace, can cause some very nasty bugs in big projects as they can be accessed from any file and hence be modified from anywhere. These are some of the reasons why global variables are considered bad −

  • Global variables can be altered by any part of the code, making it difficult to remember or reason about every possible use.

  • A global variable can have no access control. It can not be limited to some parts of the program.

  • Using global variables causes very tight coupling of code.

  • Using global variables causes namespace pollution. This may lead to unnecessarily reassigning a global value.

  • Testing in programs using global variables can be a huge pain as it is difficult to decouple them when testing.

Note that sometimes you just have to use a global variable. But before doing so make sure if you have any alternative. Read more about global variables in the c2 wiki − http://wiki.c2.com/?GlobalVariablesAreBad