Home > Article > Backend Development > The usage and function of static in c++
The static keyword in C is used to modify variables, functions, and class members, instructing the compiler to retain their scope and storage duration. Its usage includes declaring static variables to retain values across function calls or object destruction. Declare static member variables to share data between different instances of a class. Use static functions to provide class-level functionality without creating an instance of the class. Advantages of the static keyword include improved efficiency, enhanced testability, and useful when you need to retain state, share data, or provide class-level functionality.
The usage and function of static in C
What is it
static is a keyword in C used to modify variables, functions and class members. It instructs the compiler to retain its scope, storage duration, and linkage properties throughout the lifetime of the program.
Usage
Variables
<code class="cpp">int main() { static int x = 10; // 保留函数调用之间的值 return 0; }</code>
Function
<code class="cpp">class MyClass { public: static int add(int a, int b) { return a + b; } }; int main() { MyClass::add(1, 2); // 直接调用 static 函数 return 0; }</code>
Class members
<code class="cpp">class MyClass { public: static int count = 0; // 静态类变量 static void increment() { count++; } }; int main() { MyClass::increment(); // 通过类名访问 static 函数 cout << MyClass::count << endl; // 访问 static 变量 return 0; }</code>
Function
The static keyword is useful in the following scenarios:
The above is the detailed content of The usage and function of static in c++. For more information, please follow other related articles on the PHP Chinese website!