Static keyword

Static keyword

In C++, the static keyword has several different uses, depending on where it is used.

When used with a variable or function in global scope, static restricts the variable or function's scope to the current translation unit, which is the source file being compiled and any files included directly or indirectly by that file. This means that the variable or function cannot be accessed from other translation units. For example:

// file1.cpp
static int x = 5;
static void foo() { /* ... */ }

In this example, x and foo() are declared as static variables and functions in the file1.cpp translation unit. They cannot be accessed from other translation units unless they are explicitly declared as extern.

When used with a variable or function in a class or struct, static indicates that the variable or function is shared by all instances of the class or struct, rather than being associated with individual instances. For example:

class MyClass {
public:
  static int x;
  static void foo() { /* ... */ }
};

int MyClass::x = 5;

In this example, x and foo() are declared as static members of the MyClass class. x is a shared variable that is associated with the class rather than individual instances of the class. foo() is a shared function that can be called on the class itself, rather than on individual instances.

When used with a local variable inside a function, static indicates that the variable retains its value between function calls, rather than being reinitialized each time the function is called. For example: