Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

static — persistent state, internal linkage, and class members

The meaning of static depends on the declaration's location: a local variable retains state between calls, a namespace-scope name gets internal linkage, and a class member does not require a separate copy in every object. Storage duration, scope, and linkage are different concepts.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

static T name = initializer;
static R function(parameters);
struct C {
    inline static T member = initializer;
    static R method(parameters);
};

In a block, static T name = initializer; declares a variable with static storage duration: its storage lasts throughout program execution, but its name remains local. Its state does not disappear when the function returns. With thread_local, storage duration is instead associated with the thread.

Dynamic initialization of a local static variable occurs the first time control passes through its declaration; constant initialization can occur earlier. Concurrent entries wait for initialization to finish. After an exception, the next entry retries initialization; recursive entry during initialization causes undefined behavior. This protection does not synchronize later value changes.

At namespace scope, static gives a variable or function name internal linkage: it refers to an entity within that translation unit. A definition in a header included by several translation units creates separate entities. Do not confuse this with storage duration: an ordinary namespace-scope variable also has static storage duration without static, unless it is thread_local.

In a class, a static data member is not a subobject of each instance; without thread_local, objects share one member. inline static allows its definition inside the class. A non-inline member used in a way that requires a definition (odr-use) also needs an out-of-class definition. A static member function has no this, can be called as C::method(), and needs an object to access non-static data members. It cannot be virtual or qualified with const or volatile.

The example combines three uses: next_id has internal linkage, value retains the counter, and Counter::calls and Counter::next belong to the class. This entry targets C++23; the supplied source is an evolving working draft, not a frozen C++23 edition.

Examples

#include <iostream>

static int next_id() {
    static int value = 0;
    return ++value;
}

struct Counter {
    inline static int calls = 0;

    static int next() {
        ++calls;
        return next_id();
    }
};

int main() {
    std::cout << Counter::next() << '\n';
    std::cout << Counter::next() << '\n';
    std::cout << Counter::calls << '\n';
}

Result

1
2
2

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources