|
||||
|
Section 27:
|
[27.15] What's a good coding standard for using global variables? New!
[Recently created to formalize a quote from years ago (that global variable names should start with //; it's a joke; sort of). Click here to go to the next FAQ in the "chain" of recent changes]
The names of global variables should start with //. Here's the ideal way to declare a global variable: // int xyz; ←the thing that makes this global ideal is the leading //Here's the ideal way to use a global variable:
void mycode()
{
...
// do_something_with(xyz); ←the thing that makes this global ideal is the leading //
...
}
Okay, so this is a joke. Sort of. The truth is that there are cases when
global variables are less evil than the alternatives — when globals are
the lesser of the evils. But they're
still evil. So wash your hands after using them. Twice.
Instead of using a global variable, you should seriously consider if there are ways to limit the variable's visibility and/or lifetime, and if multiple threads are involved, either limit the visibility to a single thread or do something else to protect the system against race cases. Note: if you wish to limit the visibility but neither lifetime nor thread safety, two of the many approaches are to move the variable into a class as a static data member, and to use an unnamed namespace. Here is how to move the variable into a class as a static data member:
class Foo {
...
static int xyz; // See here and here for idioms about initialization order
...
}
Here is how to use an unnamed namespace:
namespace {
...
int xyz; // See here and here for idioms about initialization order
...
}
Repeat: there are three major considerations: visibility, lifetime, and thread
safety. The above two examples address only one of those three considerations.
|
|||