First take a look:
#include <stdio.h>
static int v1 = 0;
int fun()
{
static int v2 = 0;
++v2 && ++v1;
printf("%i\n", v2);
return v2;
}
int main()
{
++v1;
printf("%i\n", fun());
printf("%i\n", v1);
}
OUTPUT:
1
1
2
So the whole thing is about global static & local static variables in C, so the main property of the static variable is the fact that it's "Preserving it's value", but here it doesn't, the first piece of output is as expected : the value of v2
in fun()
should ++v2
which is 1
but the second piece is not, what expected is when it called by main()
it's preserved value would be 1
and it would again ++v2
so the second output expected to be 2
.
When we eliminate return v2
the program works as expected.
#include <stdio.h>
static int v1 = 0;
int fun()
{
static int v2 = 0;
++v2 && ++v1;
printf("%i\n", v2);
}
int main()
{
++v1;
printf("%i\n", fun());
printf("%i\n", v1);
}
OUTPUT:
1
2
2
The question is Why ? thanks.
main()
increments v1
, so its value is 1
.
When you call fun()
, it increments v2
and v1
, so v2
is 1
and v1
is 2
.
Then it prints v2
, so it prints 1
. This is the first line of output.
Then it returns v2
, so it returns 1
.
Then main()
prints the return value, so it prints 1
. This is the second line of output.
Then main()
prints v1
, so it prints 2
. This is the third line of output.
You don't call fun()
twice, so nothing in your snippet depends on whether the value is preserved. In order to see that the variable is preserved, you have to call the function again. If you add another
printf("%d\n", fun());
at the end it will print 2
twice, because the value of v2
will be preserved and incremented.
Your second code snippet produces undefined behavior because the function that's declared to return an int
doesn't return anything. It's only accidentally returning what you expect -- 2
is the return value of printf()
, since it returns the number of characters that it printed (1
followed by a newline), and that's getting left in the location that's used for the return value of the function. Change the function to do
printf("|%d|"\n", v2);
and I expect you'll get different results.