I'm revisiting static modifier concepts and I'm wondering why this is the output:
this is main()
i is 6
i is 43
i is 44
i is 43
for the following code:
// Example program
#include <iostream>
#include <string>
#include <cstdio>
void func()
{
static int i = 5;
printf("i is %d\n", ++i);
i = 42;
printf("i is %d\n", ++i);
}
int main()
{
puts("this is main()");
func();
func();
return 0;
}
I know that static means one variable per instance (at least in Java). Therefore, I understand the first three lines of the output, but then why does the static int
variable jumps right back to have a value of 44 and then ...it goes backwards and the last value is 43?
I would assume when the first function call ends then the static variable gets out of scope, but it doesn't. Neither it gets reassigned to be value of 5. I might be looking at something pretty obvious here, but I simply don't understand.
static int i = 5;
...is executed on the first call only. But
i = 42;
...sets i
's value to 42
each time you call func()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.