`static` — C++ Keyword

`static` — C++ Keyword

The static keyword in C++: controls lifetime, linkage, and class membership.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

static

Has several related meanings depending on context: (1) static local variable – persists across calls; (2) static class member – shared across all instances; (3) static free function/variable – internal linkage (file-scope only).

Syntax

static Type name;                   // static local or file-scope variable
static Type member;                 // static class data member
static return-type func(params);    // static member function
static return-type file_func();     // internal linkage

Example

#include <print>

int call_count() {
    static int count = 0;  // initialized once, persists across calls
    return ++count;
}

class Config {
public:
    static int version;    // shared across all Config instances

    static Config& instance() {    // static factory / singleton pattern
        static Config cfg;
        return cfg;
    }
};
int Config::version = 3;

int main() {
    std::println("{}", call_count());  // 1
    std::println("{}", call_count());  // 2
    std::println("{}", call_count());  // 3

    std::println("{}", Config::version);  // 3
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}