liveBook · Manning

Scope

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

Scope is the region of a C++ program in which a declared name can be accessed.

Scope is the region of a C++ program in which a declared name can be accessed. A variable's scope begins at its declaration and ends at the containing statement, block, or file. Treating scope as a maintenance detail causes real bugs: names remain visible after their useful work, inner declarations hide outer ones, and returned references can outlive their objects. section 9.1 section 11.4

Prefer the narrowest scope that matches the work:

  • Declare and initialize a variable immediately before its first use; this reduces the distance a reader must track and prevents accidental reuse. section 5.1
  • Place loop variables inside the for statement, and use an if statement initializer when a search result belongs only to that condition and its branches. section 3.1 section 5.1
  • Watch for shadowing: an inner declaration with the same name hides the outer variable, making assignments and calculations easy to misread. section 9.1
  • Never return a pointer or reference to a local object; the object goes out of scope when its function returns, leaving the result invalid. section 11.4

Mistake: keeping a search variable alive too long

An index-based search declares its iterator outside the condition, adding setup and leaving the name available beyond the decision. A modern correction keeps it in the if statement: `if (auto it = std::find(values.begin(), values.end(), key); it != values.end())` followed by the found and not-found branches. The initializer is visible only in the if statement, while the search and its test remain together. section 3.1

Mistake: shadowing a member during assignment

A `Circle` can contain a member named `radius` and accept a constructor or setter parameter with the same name. Within those functions, the parameter hides the member. An assignment such as `radius = radius` assigns the parameter to itself; explicit qualification such as `this->radius = radius` distinguishes the two names. Clearer names can avoid the trap altogether. section 9.1

Mistake: returning a local object by reference

A `catenate` function builds a local `std::string` and returns a reference to it. After the function returns, that local object is out of scope, so using the reference has undefined behavior: it may crash or appear to work accidentally. Returning the `std::string` by value gives the caller a valid result. section 11.4

Listing 3.2 Using if statement with initializer to search for a key value
int main() {
    std::vector<int> values;
    for (int i = 0; i < 10; ++i)
        values.push_back(i*2);
    int key = 4;
    if (auto it = std::find(values.begin(), 
            values.end(),key); it != values.end())             #1
        std::cout << key << " was found\n";
    else
        std::cout << key << " was not found\n";
    return 0;
}

Compare a conventional search with an if statement initializer that limits the iterator to the statement. section 3.1

Listing 5.2 Declaring variables at the point of need
int maximum(const std::vector<int>& values) {
    // assume code here...
    int max = values[0];                                    #1
    for (int pos = 1; pos < values.size(); ++pos)           #2
        if (values[pos] > max)
            max = values[pos];
    return max;
}
 
int main() {
    std::vector<int> values;
    values.push_back(1);
    values.push_back(-2);
    values.push_back(-3);
    std::cout << maximum(values) << '\n';
    return 0;
}

Inspect point-of-need declaration and for-loop scope in a maximum-value computation. section 5.1

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

How deep it goes
Explains declaration boundaries, statement and block scope, shadowing, scoped initialization, and local lifetime failures.
Examples
Demonstrates scoped searches, point-of-need maximum computation, shadowed Circle radii, and a dangling string reference.
What you can do after
Diagnose scope-related bugs and refactor declarations, searches, shadowed names, and local returns toward safer C++ code.
How it connects
Connects scope with variable shadowing, namespaces, local variables, object lifetime, for loops, and if statement initializers.

Also explained in

Compare how 21 books explain scope →

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.