Let's say I have the following code:
int i = 0;
func(i++, i++);
The increment is happening right after returning the value? Is it guaranteed that the first argument will be 0, and the second argument will be 1?
Let's say I have the following code:
int i = 0;
func(i++, i++);
The increment is happening right after returning the value? Is it guaranteed that the first argument will be 0, and the second argument will be 1?
Is it guaranteed that the first argument will be 0, and the second argument will be 1?
No. Its undefined behavior. The order of evaluation of function arguments are not guaranteed from left to right or right to left, i.e. order of evaluation is unspecified and therefore side effect on i
is unsequenced.
If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined [...]
No, your code is erroneous. There is no sequence point between the evaluation of function arguments, and two operations with side effect on the same object are only allowed if they are separated by a sequence point.
Your concept of "run instantly" doesn't exist in C. Closest comes perhaps the idea of sequenced operations, where the above mentioned sequence points forcibly separate the execution of two statements or expressions.
When you write i++
, you are asking for two things to happen:
i
and add one to iti
Now, what you have to understand is that although #1 happens immediately, #2 does not. The right way to think about #2 is that it happens "sometime later". That's why we can't say what func(i++, i++);
does. We have no way of knowing whether one of the i++
's stores its result back into i
before or after the second i++
happens.
This code is broken for two reasons:
Undefined behavior and sequence points
Why are these constructs (using ++) undefined behavior?