1. Goals
Distinguish where a variable's name can be used from how long its object lives.
Read shadowed names and local
staticvariables correctly.Return results safely without keeping aliases to objects whose lifetimes ended.
2. Prerequisites
You know variables, { ... } blocks, functions returning values, pointers,
references, and const. Remember that copying an integer produces an independent
value, while a reference provides access to an existing object.
3. Explanation
Two different questions
Scope answers: which declaration does the name score mean at this point
in the code? Lifetime answers: while the program runs, has that object
been created, and is it still alive? A name being unavailable somewhere does
not mean its object has disappeared. Conversely, a pointer being in scope
does not guarantee that the object it once pointed to is still alive.
The ordinary local int score{20}; inside the example's block has automatic
storage duration. Each execution of its declaration creates that execution's
object; leaving the block ends this object's lifetime. This is the case
described by the automatic storage rules.
You need not guess addresses or the compiler's memory layout to use it.
The inner declaration of score shadows the outer declaration. These
are still separate objects, and the outer object remains alive while the
inner block executes. Inside that block, writing score selects the inner
variable. After the block, score names the outer variable again. Reusing
a name is not a way to exchange data between the two blocks.
A local variable does not always end with a call
static int visits{0}; inside nextVisit has a local name but static storage
duration. It is initialized once and keeps its value between function calls;
it does not become 0 again whenever the function runs. main cannot use
the name visits directly, even though the object remains alive after
nextVisit returns. This differs from an ordinary local variable, as described
by the static storage rules.
The example calls the function twice, producing 1 followed by 2. Starting
the program again produces 1 and 2 again; no data has been saved to a file.
A static variable creates state shared across calls, so introduce one only
when the problem requires remembered state. This lesson does not consider
multiple threads calling the function at once.
Returning a value and keeping an alias
makeScore returns an int. The value 42 initializes saved, which has
its own lifetime. It is not an alias for the function's local score.
Ending the local variable's lifetime therefore does not remove this numeric
result from the caller.
Changing the return type to int& and returning an ordinary local variable
would give the caller a reference to an object whose lifetime has ended.
This is a dangling reference. Returning that variable's address similarly
creates a dangling pointer. Reading or writing the object through such an
alias has undefined behavior: there is no correct output to predict.
The lifetime rules restrict using an
object after its lifetime has ended.
Binding const int& to an existing variable does not keep that variable
alive longer. Some ways of directly binding references to temporary values
have separate rules; they do not imply that adding const can rescue a
reference to an ordinary local variable that is about to stop existing.
Returning a reference to a static object does not itself make the reference
dangle when the function returns. However, it couples callers to shared state;
it is not the default fix for a function that only needs to return a calculation.
4. Runnable example
Save as main.cpp and compile with C++17. No input is required.
#include <iostream>
int nextVisit() {
static int visits{0};
++visits;
return visits;
}
int makeScore() {
int score{40};
return score + 2;
}
int main() {
int score{10};
std::cout << "Outer before: " << score << '\n';
{
int score{20};
const int& alias = score;
std::cout << "Inner: " << alias << '\n';
}
std::cout << "Outer after: " << score << '\n';
int saved = makeScore();
std::cout << "Returned value: " << saved << '\n';
std::cout << "Visit: " << nextVisit() << '\n';
std::cout << "Visit: " << nextVisit() << '\n';
return 0;
}Exact output:
Outer before: 10
Inner: 20
Outer after: 10
Returned value: 42
Visit: 1
Visit: 2alias is used only while the inner score remains alive. After the closing
}, neither alias nor the inner declaration of score is available in the
rest of main. The outer value remains 10 because shadowing is not assignment.
5. Common mistakes
Treating scope and lifetime as identical: a local
staticis a counterexample.Assuming a repeated name changes the outer variable; it declares another one.
Saving a block-local variable's address and reading through it after the block.
Assuming a reference or
constprolongs an existing variable's lifetime.Seeing an old number in one run and concluding a dangling pointer is safe.
The following is a bug to recognize. Do not call it to try its output:
int& badScore() {
int score{42};
return score; // Wrong: score's lifetime ends when this function returns.
}The compiler may warn at return, but no warning does not prove safety.
Use an int return type, as in makeScore, when you need a numeric result.
6. Practice
Change the inner
20to99. Only theInnerline becomes99; bothOuterlines remain10. Explain by locating the two declarations.Add a third
nextVisit()call after the existing calls. Its line isVisit: 3. Then removestaticfromvisits: all three calls printVisit: 1.Write
int makeDouble()with a localint number{12};and returnnumber * 2. Save the result inmainand print it after the function finishes: the result must be24.In a copy of the code, try using
aliasafter the inner block. Compilation must fail because the name is out of scope. Remove that line to run again.
7. Self-check
Does shadowing an outer variable end its lifetime? Answer: no. The inner block changes name lookup, not the outer object's lifetime.
Why does
visitssurvive a function return whilemaincannot use its name? Answer: it has static storage duration, but its name has function-local scope.Does changing
badScoreto returnconst int&fix it? Answer: no.constdoes not keep that localscorealive after the call; return anintvalue when the caller only needs the numeric result.
Sample code
Source file
cpp98_foundation/10_scope_lifetime/main.cpp
#include <iostream>
int nextVisit() {
static int visits{0};
++visits;
return visits;
}
int makeScore() {
int score{40};
return score + 2;
}
int main() {
int score{10};
std::cout << "Outer before: " << score << '\n';
{
int score{20};
const int& alias = score;
std::cout << "Inner: " << alias << '\n';
}
std::cout << "Outer after: " << score << '\n';
int saved = makeScore();
std::cout << "Returned value: " << saved << '\n';
std::cout << "Visit: " << nextVisit() << '\n';
std::cout << "Visit: " << nextVisit() << '\n';
return 0;
}