liveBook · Manning

Global variable

As explained in 100 C++ Mistakes and How to Avoid Them

A global variable is a variable declared at global or namespace scope whose visibility can extend across functions within a compilation unit.

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

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains compilation-unit visibility, shadowing, naming, and namespace qualification through concrete C++ listings.
Examples
Uses Circle radius listings, a setter self-assignment, namespace qualification, and a namespaced mathematical constant.
What it assumes
Assumes basic functions and variables while developing scope, shadowing, namespaces, and qualification through examples.
What you can do after
Diagnose shadowing and disambiguate global access with namespaces, qualification, and clearer names.
How it connects
Connects global variables with scope, variable shadowing, namespaces, member variables, and the scope resolution operator.

Also explained in

Compare how 12 books explain global variable →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.