2

I know that x++ refers to post increment. It first uses the original value and then resorts to the incremented value.

But when does that actually happen? Does it happen when the next immediate line in code is executed? Does it happen when original value is returned once?

Alagusankar
  • 111
  • 1
  • 8
  • 1
    Most C++ compilers can tell you the assembly-level output of any given statement. Have a look to see what's going on at the machine level. Compiler optimizations make it hard to say what happens in general terms, it's highly situational. – tadman Apr 16 '19 at 16:21
  • 2
    **It happens between sequence points.** Other than that, it's unspecified when it happens. – pmg Apr 16 '19 at 16:24
  • Depend on architecture or machine of your system. Post increment `x++` can take internally two machine cycle(MOV, INC) or it might take just one machine cycle(INC), depends on processor. – Achal Apr 16 '19 at 16:31

1 Answers1

3

It happens between sequence points.

Other than that, it's unspecified when it happens.

Imagine this

x = y = z = 42
; // sequence point A
n = x++ + y++ + z++
; // sequence point B

At seq. point A x, y, and z are all 42; at sequence point B they are all 43. For all you care, the compiler could emit code to update all 3 variables at the same time.

// pseudo code
n = 126;
[vector increment][x,y,z];
//n = 126;
pmg
  • 106,608
  • 13
  • 126
  • 198
  • Moreover, code that depends on any more specific sequencing has undefined behavior. The canonical reference around these parts would of course be [Why are these constructs using pre and post-increment undefined behavior?](https://stackoverflow.com/questions/949433/why-are-these-constructs-using-pre-and-post-increment-undefined-behavior) – John Bollinger Apr 16 '19 at 16:46
  • 1
    It is not, other than that, unspecified. Per C 2018 6.5.2.4, the value computation is sequenced before the side effect. But I do not know if there is an expression in which this meaningfully affects the evaluation in a non-obvious way. – Eric Postpischil Apr 16 '19 at 17:12