Sobes.tech
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:

  1. Inside a function:
    • A variable declared as static retains its value between function calls.
    • It is initialized only once.
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.
  1. Inside a file (global scope):
    • static limits 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
}
  1. In a class (C++):
    • static class 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.