Junior — Middle
What is the purpose of the static keyword in C++?
sobes.tech AI
Answer from AI
The keyword static in C++ has several meanings depending on the context:
- Inside a function: a static local variable retains its value between function calls.
void func() {
static int count = 0;
count++;
std::cout << count << std::endl;
}
// Each call to func() will increase count, and the value will not reset.
- Inside a class: a static class member belongs to the class itself, not to any specific object. It is shared among all instances.
class MyClass {
public:
static int staticVar;
};
int MyClass::staticVar = 0;
// Access: MyClass::staticVar
- At the file level (global variables or functions): limits the scope of the variable or function to the current file (translation unit), preventing external linkage.
Thus, static manages the lifetime, scope, and ownership of data or functions.