`static` — C++ Keyword
`static` — C++ Keyword
The static keyword in C++: controls lifetime, linkage, and class membership.
`static` — C++ Keyword
The static keyword in C++: controls lifetime, linkage, and class membership.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
staticHas 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).
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
#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
}
namespace (not static) for file-scope linkage restriction in C++.staticint 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;
}