-3

I know how does the postincrement in C++ work. Also, the C++ standard says that the behaviour of things like y = x++ + x is undefined, as there is no guarantee for the order in which are the operands of + evaluated. However, I've heard that g++ (possibly clang too) compiles such code in a way that x is incremented really after the WHOLE expression is evaluated.

So my questions are - how does that happen? And, more importantly, how can I imitate the same behaviour with my own class and an overloaded operator? I take into account that the behaviour of my class would probably be g++-specific, undefined by the C++ standard, and generaly not a wise thing to do, but I'm asking out of curiosity.

Cris
  • 162
  • 1
  • 8
  • 1
    Hardly anyone cares about answers to questions like this because all such code is complete crap and would automatically get you fired or the lowest fail grade imaginable. – Martin James May 25 '15 at 13:40
  • Compilers are really, really, really, really, really, really complicated, and we'd have to explain them in detail from the guts out in order to properly answer this question. Frankly, there's no point. – Lightness Races in Orbit May 25 '15 at 14:09

1 Answers1

2

It happens because the compiler is free to assume that you don't write undefined code.

Since you're only allowed to increment a variable once in a statement, the post-increment can be performed afterwards while preserving the semantics.

But since your code is undefined - and it's not because the order of evaluation is unspecified, it's because the operands aren't sequenced at all - your program could do anything.

It doesn't matter that a compiler generates the same code each time; an optimiser may, and sometimes will, assume that a code path that leads to the undefined code can't happen - undefined behaviour can time travel backwards.

§ 1.9, Program execution:

However, if any such execution contains an undefined operation, this International Standard places no requirement on the implementation executing that program with that input (not even with regard to operations preceding the first undefined operation).

molbdnilo
  • 64,751
  • 3
  • 43
  • 82