Chapter 7 · Scope, Duration, and Linkage
Practice · Chapter 7

Scope, Duration, and Linkage

Short drills to make the concepts stick — predict what code prints, fix a broken snippet, or write a small function. Commit to an answer before you run anything.

7.11 — Static local variables

predict

What does this print?

Trace each call to count() carefully — decide what the static local holds before you settle on an answer.

C++
#include <iostream>

void count()
{
    static int s_calls { 0 };
    ++s_calls;
    std::cout << s_calls << '\n';
}

int main()
{
    count();
    count();
    count();
    return 0;
}
Choose the output
fix

Off-by-one in the ID dispenser

This ID dispenser should hand out 0 on the first call, 1 on the second, and so on — but it hands out 1, 2, 3 instead. Fix it.

student.cppeditable

Edit student.cpp, then Run to check it against the tests.

write

Implement a unique-event-ID dispenser

Write nextEventId() so that each call returns the next integer in sequence, starting at 100 on the first call. Use a static local variable — no global state.

student.cppeditable

Edit student.cpp, then Run to check it against the tests.

7.5 — Variable shadowing (name hiding)

predict

Shadow and scope resolution

A local variable shares its name with a global. Trace each output statement and commit to an answer.

C++
#include <iostream>

int g_score { 10 };

void show()
{
    int g_score { 99 };     // shadows the global
    std::cout << g_score << '\n';    // (A)
    std::cout << ::g_score << '\n'; // (B)
}

int main()
{
    show();
    return 0;
}
Choose the output
fix

Shadow in the branch discards the result

classify() always returns "unknown" no matter what you pass in. Find the shadow that is burying each branch's result and remove it.

student.cppeditable

Edit student.cpp, then Run to check it against the tests.