• Post Reply Bookmark Topic Watch Topic
  • New Topic

Static and nonstatic  RSS feed

 
Eric Longhorn
Ranch Hand
Posts: 40
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a question about the following code:



For this code, it prints 123.

But if I change the i variable to static:



It prints 432. Why does it do this?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically, you have two different A instances... so ... for the "i" instance variables, there are two copies (one for each instance).

In your code, you use one A instance for changing the "i" variable, and the other A instance for printing the "i" variable. Hence, the value doesn't seem to be changed... as you are printing the one that didn't change.


Now, in the case of static variables, all "i" static variables are the same variable. There is only one copy. So, even though you used one A instance for changing, and one A instance for printing, they both are using the same "i" variable.

Henry
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!