Home  >  Article  >  Backend Development  >  Do Static Variables in Member Functions Share Values Across Class Instances?

Do Static Variables in Member Functions Share Values Across Class Instances?

DDD
DDDOriginal
2024-11-09 17:01:02156browse

Do Static Variables in Member Functions Share Values Across Class Instances?

Static Variables in Member Functions: Shared or Instance-Specific?

Static variables within member functions possess unique behavior in C . Consider the class definition below:

class A {
   void foo() {
      static int i;
      i++;
   }
};

The question arises: if multiple instances of class A are created, does invoking foo() on one instance modify the static variable i for all instances?

Contrary to the expectation of individual i copies for each instance, static variables in member functions behave differently. In the given example, only one copy of the static variable i exists within the entire program.

Any instance of class A affects the same i variable, which persists throughout the program's lifetime. To illustrate:

A o1, o2, o3;
o1.foo(); // i = 1
o2.foo(); // i = 2
o3.foo(); // i = 3
o1.foo(); // i = 4

Therefore, each call to foo() for any instance of class A increments the shared i variable. These static variables provide a mechanism for sharing data across all instances of a class.

The above is the detailed content of Do Static Variables in Member Functions Share Values Across Class Instances?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn