Search code examples
cincrementdecrement

Increment and decrement operators in one statement in C


I know it is theoretically undefined behavior and of course bad style. This is the example of a school (I am not the pupil). But why do I get 7 (example a) resp. 1 (example b) out of this operation:

Online example: https://onlinegdb.com/B172lj8k8

a:

#include <stdio.h>

int main()
{
    int i = 2;
    printf("%d; i=%d", ++i + i++, i);
    return 0;
}

b:

#include <stdio.h>

int main()
{
    int i = 2;
    printf("%d; i=%d", ++i - i++, i);
    return 0;
}

In my opinion the output should be 6 and 2.

  1. Execute i++, yield 2, increment i
  2. Execute ++i yield 4
  3. Additon 2 + 4

The other example should be 4 - 2.

Exexcuting the increment in a statement seems to yield the result of the increment immediately, no matter if it is postfix or prefix, which is odd. Or do I get it wrong totally?


Solution

  • The order in which the arguments passed to a function are evaluated is not specified, and the order of evaluating the operants of + is unspecified, too.

    So in printf("%d %d", i+1, i-1), for example, you cannot rely on the order of evaluation of the arguments; i+1 might be evaluated after i-1, actually; You will not recognise, since the evaluation of the one does not effect the result of the other.

    In conjunction with "side effects" like the post-increment i++, however, the effect of incrementing i at a specific point in time might influence the result of other evaluations based on i. Therefore, it is "undefined behaviour" in C, if a variable is used more than once in an expression and a side effect changes its value (formally, to be precise, if there is no sequence point in between).