Home > Article > Backend Development > Are static variables in member functions shared across all instances of a class?
Static Variables in Member Functions: Understanding Their Behavior
In C , static variables within member functions behave differently than instance variables. Let's explore how they work using an example:
Consider the following class:
class A { void foo() { static int i; i++; } };
In this class, i is declared as a static variable within the foo member function. Static variables have a lifetime that persists throughout the entire program.
Now, let's consider what happens when multiple instances of class A are created:
A o1, o2, o3;
Is the static variable i shared among all instances of A, or does each instance have its own copy?
In C , static variables within member functions are shared among all instances of the class. This means that calling foo() on one instance of A increments the same i for all instances.
To illustrate this behavior:
o1.foo(); // i = 1 o2.foo(); // i = 2 o3.foo(); // i = 3
In this example, each instance of A calls the foo() function, incrementing the shared static variable i.
Therefore, unlike instance variables, which are unique to each instance, static variables in member functions are a single entity shared by all instances of a class. They maintain their values throughout the lifetime of the program.
The above is the detailed content of Are static variables in member functions shared across all instances of a class?. For more information, please follow other related articles on the PHP Chinese website!