1

I know in C++, you can have ++x as an lvalue and that it evaluates to x. But I ran the following code and am curious about what is going on behind the scenes.

x = 10;
++x = x + 5;

In this case the final value of x is now 15. So does cpp not try to evaluate ++x at all? Or does it do something like storing the result of ++x in a temporary address and use the old value of x itself when evaluating x+5 and then this value(15) just overwrites the temporary value(11)

There's no particular reason for running such a code and I know that. I am asking this purely out of curiosity

  • 2
    The short answer is "the compiler is written with the assumption that you won't write code like that", and so stuff breaks. – Dietrich Epp Jan 26 '22 at 04:31
  • 1
    The long answer---the way that compilers deal with variables these days is much more complicated than just storing a value in a location. Once the compiler starts working on your code, it's no longer thinking about a single variable "x", but it's processing every change that happens to x as if it were a different variable. So you'll have `x1 = 10;` and then `x2` is the result of `++x`, and then `x3` is the result of `x + 5`. This is called "SSA". The compiler may also notice that `++x = x + 5` is "impossible", which may result in a "poison" value... which means it gets deleted from your code. – Dietrich Epp Jan 26 '22 at 04:39
  • 1
    This code is equivalent to `x = 10; (x += 1) = x + 5;` The expression `x += 1` normally (except if overloaded differently) returns a reference to the variable `x`. So the compiler calculates `x + 5 -> 15`, then increases `x` by 1, then assigns `15` to `x`. (Probably the order is not strictly defined, so it would be Undefined Behaviour instead). BTW The postfix operator (normally) returns a copy of x and therefore cannot be assigned that way. – Sebastian Jan 26 '22 at 04:39
  • 1
    @Sebastian: Your second guess is correct... the order is "unsequenced", according to the standard. You cannot say that `x + 5 -> 15` happens first, or `++x` happens first... it is undefined behavior. – Dietrich Epp Jan 26 '22 at 04:48
  • Thank you @Sebastian. The example made it really clear – ARandomDeveloper Jan 26 '22 at 06:57

0 Answers0