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)
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.
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)
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.
| 归档时间: |
|
| 查看次数: |
2740 次 |
| 最近记录: |