The return statement of the function:
int fun()
{
int static n=10;
return n--;
}
uses an expression with the postfix decrement operator. The value of the expression n--
is the value of the variable n
before its decrement.
From the C Standard (6.5.2 Postfix operators)
2 The result of the postfix ++ operator is the value of the operand.
As a side effect, the value of the operand object is incremented (that
is, the value 1 of the appropriate type is added to it)....
3 The postfix -- operator is analogous to the postfix ++ operator,
except that the value of the operand is decremented (that is, the
value 1 of the appropriate type is subtracted from it).
So in the for loop
for (fun(); fun(); fun())
printf ("%d\n", fun());
you have the following.
The first expression fun()
of the for loop is evaluated only one time. After its call the variable n
within the function has the value 9
due to the postfix decrement operator.
Then the second expression fun()
that represents the condition of the for loop is evaluated. It returns the current value 9
of the variable n
and the variable is decremented and becomes equal to 8
Then within the body of the for loop the function is called again:
printf ("%d\n", fun());
This call of printf
outputs the current value of the variable n
equal to 8
and the variable is decremented. Now its value is 7
. Within the third expression of the for loop the function is called one more time and the value of the variable n
becomes equal to 6
.
After that the condition expression again is evaluated. The function returns the current value 6
of the variable n
and the variable is decremented. Its value now is equal to 5
.
In the call of printf
this value 5
is outputted while the value of the variable n
itself becomes equal to 4. After the evaluation of the third expression of the for loop the variable n
becomes equal to 3. This value is returned by the function in the condition of the for loop and the variable itself becomes equal to 2. And this value is outputted in the call of printf.
In the call of printf
this value 2
is outputted and variable n
is decremented and is equal to 1
.
Then due to the third expression of the loop the variable n
is decremented and becomes equal to 0
. This value is returned by the function call in the condition expression. So the loop stops its iteration. At the same time the value of the static variable n
within the function becomes equal to -1
.
So the for loops outputs the following values:
8
5
2
If you will add one more call of printf
after the for loop:
for (fun(); fun(); fun())
printf ("%d\n", fun());
printf ("%d\n", fun());
then the output will be:
8
5
2
-1