Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 171 ยท Functions

Scope, Lifetime and Storage Duration

Understand C++ scope and lifetime - block and global scope, shadowing, automatic, static, dynamic and thread storage duration, static local variables, and global variable pitfalls.

Every variable in C++ has two separate properties that beginners often blur together. Its scope is where in the source code the name can be used. Its lifetime is when during execution the object actually exists in memory. A name can be out of scope while its object is still alive (a static local between calls), and, more dangerously, a name or pointer can still be around after its object has died (a dangling reference).

C++ gives you precise control over both. That control is what makes RAII, deterministic destructors and zero-overhead abstractions possible, and getting it wrong is behind many of the language's classic bugs. In this lesson you'll learn the kinds of scope, the four storage durations (automatic, static, dynamic and thread), what the overloaded keyword static means in each place, why global variables cause trouble, and how shadowing can hide bugs. You'll build on Functions and Recursion, where you met stack frames.

Scope: where a name is visible

A name is visible from its point of declaration to the end of the region it was declared in:

  • Block scope: declared inside { } (a function body, a loop, an if). Visible until the closing brace. Function parameters have block scope in the function body.
  • Namespace scope: declared outside any function or class. Visible from the declaration to the end of the file. Names declared outside every namespace are in the global namespace ("global scope").
  • Class scope: members of a class, visible inside the class and through objects (obj.member).

Variables declared in the head of an if, switch, for or while (including C++17 if (init; condition)) are scoped to that whole statement, including its else:

C++ Block scope in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The guideline is simple: declare variables in the smallest scope that works, as late as possible, ideally where you can initialize them. Small scopes make code easier to read, let the compiler catch misuse, and free resources sooner.

Shadowing

A name declared in an inner scope hides (shadows) the same name from an outer scope. That's legal, and it's a common source of bugs:

C++ Shadowing hides the outer variable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The programmer probably meant to update count, but the int in front of it inside the loop declared a brand-new variable. The outer count stays 0. The global can still be reached with the scope resolution operator ::limit.

GCC doesn't warn about shadowing with -Wall -Wextra. Add -Wshadow to your own builds (see Compilers, Flags and Optimization); many teams treat it as an error. Shadowing is also why many codebases give data members a distinct style such as count_ or m_count.

Lifetime and storage duration

Storage duration decides when an object's memory is set aside and when it's released. C++ has four:

Storage duration Created Destroyed Typical examples
Automatic when execution reaches the declaration at the end of the enclosing block local variables, parameters
Static before main (globals) or on first use (static locals) after main returns globals, static locals, static members
Dynamic when you call new (or a container/smart pointer does) when delete runs objects owned by std::unique_ptr, vector elements
Thread when the thread starts (or on first use) when the thread ends thread_local variables

Automatic storage: the stack

Local variables have automatic storage. They live in the function's stack frame, are created when execution reaches their declaration, and are destroyed in reverse order when their block ends, whether by falling off the end, return, break or an exception. For class types, "destroyed" means the destructor runs at a precisely known point:

C++ Automatic objects die at the closing brace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

This deterministic destruction is the foundation of RAII: wrap a resource (a file, a lock, memory) in an object whose destructor releases it, and the resource is freed exactly when the object goes out of scope. You'll use it everywhere from Destructors and RAII onward.

Automatic storage is also why returning a pointer or reference to a local is a bug: the object is gone the moment the function returns (see Returning Values).

Static storage: lives for the whole program

Objects with static storage duration exist for the whole run of the program. There are three kinds:

  • Global variables and other namespace-scope variables.
  • static data members of classes (see Static Members).
  • static local variables, declared with static inside a function.

Unlike automatic variables, static-storage objects that you don't initialize are zero-initialized, so a global int starts at 0. (Relying on that is still unclear code; initialize explicitly.)

static local variables

A static local variable has block scope (only its function can see it) but static lifetime (it survives between calls). It's initialized once, the first time execution passes its declaration:

C++ static locals remember between calls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The message (building the greeting) appears only once: the initializer of a static local runs the first time execution reaches it, and later calls skip it. The tickets are taken in separate statements on purpose. In std::println("{} {} {}", next_ticket(), next_ticket(), next_ticket()), the order in which the three arguments are evaluated is unspecified, so the numbers could come out in any order (GCC happens to print 3 2 1). Returning a reference to text is fine, because a static local outlives every call.

Three properties make static locals especially useful:

  • Lazy: the object is only created if the function is actually called. Expensive setup (a lookup table, a configuration) costs nothing for programs that never need it.
  • Thread-safe initialization: since C++11, if several threads call the function at once, exactly one initializes the variable and the others wait. (Later modifications, like ++counter, are not synchronized; that needs a mutex or std::atomic.)
  • Defined order: it's created when first used, which avoids the global initialization order problem described next.

The trouble with global variables

Mutable global variables are tempting because every function can reach them. That's exactly the problem:

  • Hidden dependencies. A function's signature no longer tells you what it reads or changes. Any call anywhere might modify the global.
  • Hard to test. Tests share the global state and affect each other.
  • Data races. Two threads touching a global without synchronization is undefined behavior.
  • Initialization order across files. Globals in one .cpp file are initialized in order, but the order between files is unspecified. If a global in a.cpp uses a global from b.cpp during its own initialization, it might see an object that hasn't been constructed yet. This is the "static initialization order fiasco":
C++
// registry.cpp
std::vector<std::string> registry;          // a global

// plugin.cpp
extern std::vector<std::string> registry;
bool registered = (registry.push_back("csv"), true);   // may run BEFORE registry is constructed!

The standard fix is to replace the global with a function returning a static local, the "construct on first use" pattern:

C++
std::vector<std::string>& registry() {
    static std::vector<std::string> instance;   // created on the first call, whoever calls first
    return instance;
}

Better still, pass what a function needs as a parameter. Global constants (constexpr, const) are fine: they can't change, so they have none of these problems.

static at namespace scope: internal linkage

When static appears on a variable or function at namespace scope, it means something completely different: internal linkage. The name is private to its .cpp file, so another file can have its own function with the same name without a clash:

C++
// parser.cpp
static int helper(int x) { return x * 2; }   // only parser.cpp can call this

Modern C++ prefers an anonymous namespace for this purpose, because it also works for types. You'll see it in Namespaces. Here's the full list of meanings of static:

Where Meaning
Local variable static storage duration (lives for the whole program, initialized once)
Namespace-scope variable or function internal linkage (private to this file)
Class data member one shared variable for the class, not one per object
Class member function called without an object; has no this

Dynamic storage: you decide

Objects created with new live until delete destroys them, regardless of scope. The pointer holding the address is an ordinary automatic variable, so it's easy to lose the pointer while the object lives on (a leak) or delete the object while pointers still refer to it (a dangling pointer).

Modern C++ almost never uses raw new and delete directly. Containers like std::vector manage dynamic storage for their elements, and smart pointers tie a dynamic object's lifetime back to a scope:

C++
#include <memory>

void load() {
    auto image = std::make_unique<Image>(1920, 1080);   // dynamic object
    image->decode();
}   // the unique_ptr goes out of scope and deletes the Image automatically

The details are in Dynamic Memory: new and delete and Smart Pointers: std::unique_ptr. The memory layout lesson shows where each kind of storage lives in memory.

Thread storage: one copy per thread

A variable declared thread_local gets a separate instance for each thread. Each thread's copy is created when the thread first uses it (or at thread start) and destroyed when the thread ends. It's useful for per-thread caches, random number generators and counters that must not be shared:

C++ One counter per thread

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Each thread reports only its own work (100, 200 and 300 operations), and the main thread's copy stays 0. The lines from the three threads may appear in any order, because the threads run at the same time; press Run a few times and the order can change. You'll learn about std::jthread in Threads.

Storage class keywords at a glance

C++ has a small set of keywords that control storage duration and linkage. Their meanings have shifted over the years, so a map helps:

Keyword Meaning today
auto Not a storage class any more. Since C++11 it means "deduce the type" (auto). Locals are automatic by default.
register Removed. It was a hint to keep a variable in a CPU register; C++11 deprecated it and C++17 removed it. The compiler decides better than you.
static Static storage duration. On a local variable: one instance, initialized on first use. At namespace scope: internal linkage. On a class member: shared by all objects (static members).
extern Declares a variable or function that is defined in another translation unit, without creating it. Gives external linkage.
thread_local One instance per thread.
mutable Not about storage duration at all: it lets a data member be modified inside a const member function (const member functions).

extern across files

A global variable can be defined only once in the whole program, but it can be declared in any number of files. The usual pattern puts an extern declaration in a header and the single definition in one .cpp file:

C++
// config.h
extern int retry_limit;          // declaration only: no storage is created here

// config.cpp
#include "config.h"
int retry_limit = 3;             // the one definition

// main.cpp
#include "config.h"
int main() { return retry_limit; }   // the linker connects it to config.cpp

If you wrote int retry_limit = 3; in the header instead, every file including it would define its own copy and the linker would report a duplicate symbol. Since C++17, inline int retry_limit = 3; in a header is also legal: the variable may be defined in many files and the linker keeps one. And a const variable at namespace scope has internal linkage by default, so const int max_size = 10; in a header gives each file its own private copy, with no conflict.

C++ Every storage keyword in one program

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

shared_count is found through its earlier extern declaration; mutable lets compute() fill the cache even though cache is const; and next_id keeps its counter between calls, printing ids: 1 then 2.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? int f() { static int n = 10; return n++; } called as f(); f(); std::println("{}", f());

    n is initialized to 10 once. The first call returns 10 (n becomes 11), the second returns 11 (n becomes 12), and the third returns 12.
  2. 2. int x = 1; { int x = 2; x = 3; } std::println("{}", x); What is printed?

    The inner int x shadows the outer one, so x = 3 changes only the inner variable, which is destroyed at the closing brace. The outer x is still 1.
  3. 3. Objects a, b and c are declared in that order inside one block. In what order are their destructors called when the block ends?

    Automatic objects are destroyed in reverse order of construction, at the end of their block.
  4. 4. What does static mean on a function defined at namespace scope in a .cpp file?

    At namespace scope, static gives internal linkage. Other files can't call it and may define their own function with the same name. An anonymous namespace does the same in modern code.
  5. 5. Why is replacing a global with a function that returns a static local a common fix for initialization-order bugs?

    Globals in different files are initialized in an unspecified order. A static local is initialized the first time execution reaches it, so every user gets a fully constructed object.

Summary

  • Scope is where a name is visible (block, namespace, class); lifetime is when the object exists. They are related but not the same.
  • Declare variables in the smallest scope possible. Inner declarations shadow outer ones; use -Wshadow to catch it and ::name to reach a global.
  • Automatic objects are created at their declaration and destroyed in reverse order at the end of their block. That determinism powers RAII.
  • Static storage lasts the whole program: globals, static members and static locals, which are initialized once, lazily and thread-safely.
  • Avoid mutable globals: hidden dependencies, test interference, data races and the initialization order fiasco. Prefer parameters, or construct-on-first-use functions.
  • static at namespace scope means internal linkage, which is a different meaning entirely.
  • Dynamic objects live until deleted; let containers and smart pointers manage them. thread_local gives each thread its own copy.

Next: Namespaces, where you'll organize names into groups so large programs and libraries don't collide.