Why is the return value of the fun function 8 instead of 7?
When writing return (x=x+2,x+1)
, the first expression is evaluated first so x=x+2
is evaluated, causing x to equal 7 as a side effect. Then the second expression is evaluated and returned, hence the function returns x+1 hence returns 8.
If you had written return (x+2,x+1);
, the result would have been 6 because the first expression x+2
doesn't have any side effect.
Both parts in the return
are evaluated respectively and the result of the last instruction is returned:
At first we have:
x = x + 2 // 7
Now x
is updated to 7
before the second evaluation which gives:
x + 1 // 7 + 1 = 8
and finally return 8
.
For better understanding consider the case of intermediate variable as follows:
return (y = x + 2, y + 1);
The statement return (x = x + 2, x + 1);
is equivalent to:
x = x + 2; // x == 7
return x + 1; // returns 8
The QA you conveniently linked states
The comma operator evaluates a series of expressions. The value of the comma group is the value of the last element in the list.
so the value of
x+2,x+1;
is x+1
and there are no side effects.
Sample code:
#include<stdio.h>
int main(int argc, char * argv){
int x;
x = 0;
x = (x+2, x+1);
printf("%d\n", x);
return 0;
}
results in 1
when run.
However, when you do
return (x=x+2, x+1)
you do have a side effect: x
is incremented by two first, then x
is incremented by 1 and the result is returned.