-6

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?

Christian
  • 3,503
  • 1
  • 26
  • 47
  • 1
    As you know that it is UB, where "everything" can happen, why are you wondering at all? – Stephan Lechner Dec 29 '19 at 22:09
  • I am wondering how a beginner should know that and the teacher expects an answer. And no matter how I calculate in my head, I never get to 7 – Christian Dec 29 '19 at 22:16
  • 1
    Because it's undefined behavior. The compiler is allowed to do anything with the code, the compiler can just optimize it to `int main() { printf("%d; i=%d", 7, 4); }` and [this most probably happens](https://godbolt.org/z/YEsmZF), but I don't know compiler options used in onlinegdb. There is no calculation. There is no sense. – KamilCuk Dec 29 '19 at 22:18
  • 2
    "I know it is theoretically undefined behavior " is not compatible with "In my opinion the output should be" . If you think there should be certain output, it shows you do not understand that it is undefined – M.M Dec 29 '19 at 22:28
  • @M.M What does the compiler do, to get to 7 resp 1? Just wondering, what is going on here? – Christian Dec 29 '19 at 23:27
  • Use you debugger to step through the assembler. Since your code has UB, only you can trace through to find out what is happening in your environment. – Martin James Dec 30 '19 at 03:59

1 Answers1

2

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).

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58