Junior — Middle
What is the role and application of the static keyword in programming?
sobes.tech AI
Answer from AI
In C/C++, the keyword static has several uses related to the scope and lifetime of variables and functions:
- Inside a function:
- A variable declared as
staticretains its value between function calls. - It is initialized only once.
- A variable declared as
void func() {
static int count = 0;
count++;
std::cout << count << std::endl;
}
// Each call to func() increases count, and the value is preserved between calls.
- Inside a file (global scope):
staticlimits the scope of a function or variable to the current file (translation unit).- This prevents name conflicts during linking.
static void helper() {
// This function is only visible within this file
}
- In a class (C++):
staticclass members belong to the class itself, not to any specific object.- Shared among all instances.
class MyClass {
public:
static int count;
};
int MyClass::count = 0;
Thus, static manages the lifetime, scope, and ownership of variables and functions.