Reputation: 41
While understanding side effects in programming, I came across this code:
int add(int x, int y)
{
return x + y;
}
int main()
{
int x = 5;
int value = add(x, ++x); // is this 5 + 6, or 6 + 6? It depends on what order your compiler evaluates the function arguments in
printf("%d",value);
return 0;
}
I do not understand why the output here is order-dependent. I mean, if the first argument is evaluated first, then x is 5. Then ++x is evaluated, which changes x to 6. My doubt is that x has been changed to 6, this means that x in the first argument should also become 6. Therefore the function call effectively should be add(6,6);
, which is the same if the second argument was evaluated first. Then why does the writer say that the result depends on the order of evaluation of the operands? Please explain. I am getting really confused while understanding side effects.
Upvotes: 2
Views: 145
Reputation: 781068
Since functions receive their arguments by value, calling a function with expressions is equivalent to assigning those expressions to temporary variables, then calling the function with those variables. So
add(x, ++x);
If the arguments are evaluated left-to-right, it's equivalent to:
temp1 = x; // temp1 = 5, x = 5
temp2 = ++x; // temp2 = 6, x = 6
add(temp1, temp2); // add(5, 6)
If they're evaluated right-to-left, it's equivalent to:
temp2 = ++x; // temp2 = 6, x = 6
temp1 = x; // temp1 = 6, x = 6
add(temp1, temp2); // add(6, 6)
C doesn't specify the order that arguments are evaluated, and specifically states that code like this produces undefined behavior because of it.
Upvotes: 1