A global variable is visible to functions in a compilation unit from its declaration to the source file’s end. That convenience makes correctness and readability easy to lose, especially when local, parameter, and member names shadow it. section 9.1
Mistake: identical names hide the variable you intended
In Listing 9.1, the global rad, Circle::rad, constructor parameter, and setter parameter share a name. Inside setRadius, rad = rad assigns the parameter to itself, so the member never changes. Prefer distinct, expressive names; when a global is unavoidable, use a namespace and qualify it explicitly. section 9.1
Listing 9.3 Identical variable names distinguished by a namespace
namespace global { #1
double radius = 1.0;
};
class Circle {
private:
double radius;
public:
Circle(double radius) : radius(radius) {}
void setRadius(double radius) {
if (radius < 0)
throw std::invalid_argument("negative radius");
this->radius = radius; #2
}
double sum() const {
return radius + global::radius; #3
}
double getRadius() const { return radius; }
};
int main() {
Circle c(3);
std::cout << "radius is " << c.getRadius() << '\n';
std::cout << "enlarged radius is " << c.sum() << '\n';
return 0;
}
The corrected pattern places the global in namespace global, uses this->radius for the member, and writes global::radius when the global is intended. section 9.1
Use short global names only for universally recognized values such as PI or E; otherwise choose a conspicuous name or namespace. In legacy code, improve names and qualification incrementally, testing each change. section 9.1











