> Well this is not global variables. More like file-scope ones.
There is no scope called file-scope in C++. It is a variable at namespace-scope.
The outermost declarative region of a translation unit is also a namespace, called the global namespace. A name declared in the global namespace has global namespace scope (also called global scope). -IS
A variable declared at namespace scope may have either internal linkage (as in the example above)
or external linkage (as for std::cout).
// namespace scope
// this is frowned upon due to being able to accidentally change it
// later in the code and not catch it, causing all kind of bugs
int SCREEN_W = 640;
// this is perfectly fine because it is constant and can't be
// changed to cause unexpected bugs
constint SCREEN_H = 480;
I use constant globals regularly. I think the thing that most frown on is what I pointed out, the issue of changing the non-const globals which can lead to bugs.
1 2 3 4 5 6 7 8
// collision detection code messed up
// checking to see if the screen width is
// equal to the right wall of a sprite (object a member x + objec width
if (SCREEN_W = ObjA.x + w){ // meant to do == instead of = so changed 640 to new value (say 64)
//......
// now anything dealing with SCREEN_W will cause funky
// screens, bugs, or possibly crashes
}
Changing non-const globals is a manifestation of the fundamental issue:
programmatic visibility of variables ant namespace scope leading to tight coupling.
1 2 3 4 5 6 7 8 9 10 11 12
int a = 640; // programatically visible and changeable from other translation units.
// tight coupling
externconstint b ; // programatically visible in other translation units.
constint b = 640 ; // but not changeable
// still not ideal because someone could write code relying on 'b' being defined
// or worse: relying on 'b' having a value of 640
// looser coupling
staticint c = 640 ; // programatically not visible in other translation units.
// that there is a global 'c' is an implementation detail that is not visible to other components.
// no coupling