Home >Backend Development >C++ >How Do Static Variables Behave within Member Functions in C ?
Static Variables within Member Functions in C
In C , member functions can contain static variables. A static member variable within a class is shared across all instances of the class, regardless of the object on which the function is called.
Let's consider the following class:
class A { public: void foo() { static int i; i++; } };
Contrary to the assumption that each instance of A would have its own copy of i, it's important to note that there will be only one instance of i for the entire program. This is because static int i is declared inside the class definition and outside any specific function, making it a member of the class itself rather than a local variable to the foo function.
Hence, any instance of an A object will affect the same shared i, and its lifetime will persist throughout the program's execution. For example:
A o1, o2, o3; o1.foo(); // i = 1 o2.foo(); // i = 2 o3.foo(); // i = 3 o1.foo(); // i = 4
In this scenario, all instances of A access and modify the same static variable i. Calling foo on any instance increments the shared i for the entire class.
The above is the detailed content of How Do Static Variables Behave within Member Functions in C ?. For more information, please follow other related articles on the PHP Chinese website!