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.