Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading