The role of static in C
In C, the static keyword is used to control the scope and life cycle of variables, functions and classes.
Variables
- Variables declared as static inside a function are called static local variables.
- Static local variables are initialized the first time the function is executed and remain throughout the life cycle of the function.
- The value of a static local variable remains unchanged even if the function returns or leaves its scope.
Function
- A function declared as static outside a class is called a static member function.
- Static member functions can only access static member variables of the class and cannot access non-static member variables.
- Static member functions cannot operate on this pointer.
Class
- Use the static keyword in a class declaration to create static member variables.
- Static member variables exist throughout the life cycle of the program, even if no instance of the class is created.
- Static member variables are shared among all instances of the class.
Other usage
-
Type Inlining(Type Inlining): static member functions can be inlined into the class definition to improve performance.
-
Function Inlining: Static functions can be inlined into the functions that call them, avoiding the overhead of function calls.
-
Constant Definition: Using the static keyword in a constexpr expression creates a constant that is known even at runtime.
Summary
- The static keyword can control the scope and life cycle of variables, functions and classes in C.
- Static local variables remain unchanged throughout the life cycle of the function.
- Static member functions can only access static member variables of the class and cannot operate on the this pointer.
- Static member variables are shared among all instances of the class.
- The static keyword is used for other purposes, such as type inlining, function inlining, and constant definition.
The above is the detailed content of The role of static in c++. For more information, please follow other related articles on the PHP Chinese website!