-1

Here is a code:

#include<stdio.h>

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

The output to the code is

2 1 2

But, if the code is evaluated right to left then it should be

2 1 1

Please explain how GCC is evaluating.

Thank you.

Rishi
  • 1,987
  • 6
  • 32
  • 49
  • As far as I know, this is undefined behaviour. But I'm pretty sure someone has the standard at hand and will give details about it in an excellent answer soon (or link one). – Jonas Schäfer Sep 12 '13 at 09:48
  • Just to bring you the meaning of undefined behavior closer (as you maybe don't get it right). i.e. gcc 1.7 wouldn't do one of the both, it would probably just let your code execute a linked linux game. As the gcc 1.7 had the easteregg of just let your executabel start games when the compiler detects UB. and even this eastegg isn't breakign any of the ISO C rules. as they say, the compiler is free to do anything as UB is detected. – dhein Sep 12 '13 at 10:16

2 Answers2

1

There is no priority, this is undefined behavior, because you arent allowed to change the same value in a single invokation multiple times.

From c99 ISO/IEC 9899:TC3 -> Apenndix J:

J.2 Undefined behavior 1 The behavior is undefined in the following circumstances:

[...]

— Between two sequence points, an object is modified more than once, or is modified and the prior value is read other than to determine the value to be stored (6.5).

dhein
  • 6,431
  • 4
  • 42
  • 74
  • But there is no permutation in which the output should be as it is. – Rishi Sep 12 '13 at 09:50
  • @Rishi That is the point of this being undefined behavior: it *does not* have to act as if one "reasonable" permutation is taken. Anything could happen, since you did something you're not supposed to do. – unwind Sep 12 '13 at 09:52
  • @Rishi yeah, as unwind already said, the standard says (I citate it in my own words)"if at any moment the code will be able to invoke undefined behavior, from this moment on the code is allowed to do anything.". So your printf could even put out "I love to throw Bananas" without the compiler haven't respected the standard at any time, you udnerstand that explenation?:) – dhein Sep 12 '13 at 10:11
0

Order of evaluation of function arguments is unspecified, from C99 §6.5.2.2p10:

The order of evaluation of the function designator, the actual arguments, and subexpressions within the actual arguments is unspecified, but there is a sequence point before the actual call.

João Fernandes
  • 1,101
  • 5
  • 11