Why is this an issue?
A global variable can be modified from anywhere in the program. At first, this might look convenient, but in fact, it makes programs very hard to
understand: When you see a function call, you cannot know if the function will affect the value of the variable or not. You have lost the ability to
reason locally about your code and must always have the whole program in mind.
Additionally, in multi-threaded environments, global variables are often subject to race conditions.
Some global variables defined in external libraries (such as std::cout
, std::cin
, std::cerr
) are fine to
use, but you should have a good reason to create your own. If you do use a global variable make sure that they can be safely accessed
concurrently.
This rule detects all declarations of global variables (in the global namespace or in any namespace) that are not constant.
Noncompliant code example
double oneFoot = 0.3048;
double userValue;
void readValue();
void writeResult();
int main() {
readValue();
writeResult();
}
Compliant solution
constexpr double footToMeter = 0.3048;
double readValue();
void writeResult(double);
int main() {
auto userValue = readValue();
writeResult(userValue * footToMeter);
}
Resources