It is not that global variables are bad. They are neither good nor bad, but as any tool, they are useful when are serving their purpose. Since this particular tool tends to be abused, there is a general notion 'global variables are bad, ooooggggh'. Still, there are global variables everywhere. For instance, std::cout
is often a global variable.
However, certain scenarios demand global variables. But having read that 'they are bad' people start using something else - usually Singletons. Singletons are no better than global variables with the only exception of lazy iniatilization - but many singletons are not even using lazy initialization. As a result of this approach, every global variable is turned into Singleton (luckily it's already supported by many libraries, and turning global into singleton takes no more than several keystrokes) and the same abuse continues.
Instead of repeating 'global variables are bad' mantra, developers should understand what issues are associated with them, what are their benefits and choose a tool which suits the particular coding need.
Global variables make reasoning about the code hard. What it means is that since any function can write the value into it, it is hard to understand how the value changes over program execution. If, for instance, you realize that the value at some point is incorrect, you will have time figuring out how you ended up there. In worst case, you will have to grep the whole codebase for the name of this variable, which will be funny if codebase is 1000 of files, and name is something like i
.
I will not tell you what to use in your case. There are already suggestions: make it a static variable of the class or make it local variable to the given .cpp file. Both are good, since they limit the scope of potential variable changers - to friends of class, or to functions defined in the same .cpp file. Taking class approach, you can have the functions and the data both static members of the class - this way you wan't need to define friends. Choice is yours.