Is post-increment operator guaranteed to run instantly?

132 views Asked by At

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?

4

There are 4 answers

1
Lundin On BEST ANSWER

This code is broken for two reasons:

  • Accessing a variable twice between sequence points, for other purposes than to determine which value to store, is undefined behavior. There are no sequence points between the evaluation of function parameters. Meaning anything could happen, your program might crash & burn (or more likely display incorrect or garbage values).
  • The order of evaluation of function parameters is unspecified behavior, meaning you can't know which one that will be evaluated first.

Undefined behavior and sequence points

Why are these constructs (using ++) undefined behavior?

4
haccks On

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.

C11:6.5 Expressions (p2)

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 [...]

0
Jens Gustedt On

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.

4
Steve Summit On

When you write i++, you are asking for two things to happen:

  1. fetch the value of i and add one to it
  2. store the result back into i

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.