A global variable can be modified from anywhere in the program. At first, this might look convenient, but it makes programs harder 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, global variables are often subject to race conditions in multi-threaded environments.
Some global variables defined in external libraries (such as std::cout
, std::cin
, std::cerr
) are acceptable
to use, but you should have a good reason to create your own. If you use a global variable, ensure they can be safely accessed concurrently.
This rule detects all declarations of global variables (in the global namespace or any namespace) that are not constant.
Noncompliant code example
double oneFoot = 0.3048; // Noncompliant
double userValue; // Noncompliant
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);
}