C++ Static Variables (static): Functions and Usage Scenarios
The core difference when the `static` keyword in C++ modifies variables, functions, and class members lies in **scope** and **lifetime**. Below are three typical scenarios and characteristics of static variables: ### 1. Local Static Variables (Within Functions) Modified with `static` inside a function, their scope is limited to that function, with a lifetime spanning the entire program. Initialization occurs on the first call (default 0). Used to "remember" state between multiple function calls (e.g., counters), avoiding global variable pollution. ### 2. Global Static Variables (Within a File) Modified with `static` outside a function, their scope is restricted to the current source file, with a program-level lifetime. Initialization happens before `main()`. Used for file-private global data, preventing cross-file naming conflicts (compared to ordinary global variables). ### 3. Class Static Member Variables (At Class Level) Declared inside a class and initialized outside, shared by all instances with a program-level lifetime. Used for cross-instance shared data (e.g., counting instances), accessed via `ClassName::`, avoiding dependencies on uninitialized variables. **Notes**: Avoid overusing static variables (prone to multi-threaded race conditions), pay attention to initialization order, use `ClassName::` for explicit access, and apply static variables reasonably.
Read More