Search code examples
c++c++17undefined-behaviorexpression-evaluation

Trying to understand --x vs x-- in C++


I am trying to evaluate this, and even if is is quite simple, I can't seem to understand it. I got 16, but the provided answer was 12. I don't understand how this can be 12.

I did --x first, so first y would be 4, then I need to multiply with x--, but it will be 4 too since it is evaluated after, and the x being decremented after that to 3. So 4*4 = 16.

Can someone explain what is wrong in my reasoning?

int x, y;
x = 5;
y = --x * x--;
std::cout << y;

Solution

  • You are not guaranteed whether --x or x-- is evaluated first, so the result is undefined.