-1

I have been having some trouble to understand this operation and why it gives the result it gives

int x = 5;
std::cout<<++x*x--<<std::endl;

Why is the result 30 and not 36? Isn't it supposed to perform (++x) first so we have 6 and then (x--) which is post decrement, so we end up with 6*6 for a result of 36. But when I tried running this code I get 30. Can someone explain whats going on here?

  • 1
    Recommended reading: [Undefined behavior and sequence points](https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) – user4581301 May 22 '22 at 16:44
  • 1
    The rules changed in C++17, but not with respect to this case. – user4581301 May 22 '22 at 16:44
  • It's because the order of evaluation is undefined. Depends on your compiler. It's probably first evaluating the right hand side of the multiplication and then the left hand side of it. So the result becomes 6*5 == 30 but you should not rely on such expressions. Their results can vary a lot. – digito_evo May 22 '22 at 16:54
  • I am not willing on using these expressions, but it was a question asked in an interview so made me wonder how it's processed to give this result. The operation was done using c++17 – Amir3022 May 22 '22 at 17:22
  • It's a common trick question to see the depth of an applicant's understanding of C++. The correct answer is "I dunno. It's not specified by the C++ Standard." When it's not a trick question and the interviewer wants a hard number as an answer you need to think twice about whether or not you want the job. – user4581301 May 22 '22 at 22:49
  • Unfortunately, they wanted a hard number and I was rejected anyway. But this particular question really bothered me since I tried many different combinations of pre and post increments in the same operation, and still couldn't understand the order of operation. But now reading about Undefined Behavior, I have better knowledge of what's going on – Amir3022 May 23 '22 at 10:04

0 Answers0