What is the static keyword in C++?

  • Static local variable: keeps its value between calls.
  • Static data member: one copy for the whole class.
  • Static member function: can be called without an object, and has no this.
  • Static at file level: the name is visible only in that file.
#include <iostream>

int next_id() {
    static int id = 0;           // set only once
    return ++id;
}

struct Counter {
    static inline int total = 0;
    Counter() { total++; }
};

int main() {
    std::cout << next_id() << next_id() << next_id() << '\n';
    Counter a, b;
    std::cout << Counter::total << '\n';
}
Output

123
2

See Static Members.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.