Why is the return value of the fun function 8 instead of 7?

Ash*_*mar 35 c return-value comma

With reference to Comma-Separated return arguments in C function [duplicate] ,

x=x+2,x+1;
Run Code Online (Sandbox Code Playgroud)

will be evaluated as

x=x+2; 
Run Code Online (Sandbox Code Playgroud)

However, in case of the following code

#include<stdlib.h>
#include<stdio.h>

int fun(int x)
{
    return (x=x+2,x+1); //[A]
}

int main()
{
   int x=5;
   x=fun(x);
   printf("%d",x); // Output is 8
}
Run Code Online (Sandbox Code Playgroud)

Shouldn't line [A],be evaluated as

x=x+2;
Run Code Online (Sandbox Code Playgroud)

giving x = 7

小智 56

The statement return (x = x + 2, x + 1); is equivalent to:

x = x + 2; // x == 7
return x + 1; // returns 8
Run Code Online (Sandbox Code Playgroud)

  • +1。为了直接解决OP的困惑,语句“ x = x + 2,x + 1;”等效于一对语句“ x = x + 2;”。x +1;`。只是语句“ x +1;”实际上并没有“做任何事”,因此我们可以忽略该语句,说它等同于“ x = x + 2;”。当添加`return`时,显然`return x + 1;'语句不再是空操作,因此我们不能再忽略它了。:-) (8认同)

Cor*_*ane 15

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.

  • @AshishKumar,因为它更改了x的值。并不是真正的“副作用”,因为它仍然是显性的,但是它导致`x`在逗号的右边不同。 (6认同)

XBl*_*ode 12

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
Run Code Online (Sandbox Code Playgroud)

Now x is updated to 7 before the second evaluation which gives:

x + 1 // 7 + 1 = 8
Run Code Online (Sandbox Code Playgroud)

and finally return 8.

For better understanding consider the case of intermediate variable as follows:

return (y = x + 2, y + 1);
Run Code Online (Sandbox Code Playgroud)

  • nitpick:是逗号运算符来评估两个部分并返回后者。它不是特定于`return`语句的,与`y =(x = x + 2,x + 1)`会得到相同的效果。 (2认同)

luc*_*rot 6

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;
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

results in 1 when run.


However, when you do

return (x=x+2, x+1)
Run Code Online (Sandbox Code Playgroud)

you do have a side effect: x is incremented by two first, then x is incremented by 1 and the result is returned.