Pre & post fix together - Why is not working? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Pre & post fix together - Why is not working?

int x=1; cout << ++x++; //Wrong but: cout << (++x)++; //OK is Ok. - Why?

19th Nov 2016, 8:22 PM
Marcin
Marcin - avatar
2 Answers
+ 2
This is just a guess, but I think ++x++ is the same as ++(x++), since the postfix operation seems to have a higher priority. ++(x++) doesn't work, because it basically says: "increment x++ before printing it", but the x++ part would already do the printing before the prefix operation took effect. (++x)++, however, increments x (postfix) after printing it after incrementing It (prefix), so there is no conflict between the prefix and the postfix operation and therefore it works this way.
19th Nov 2016, 11:13 PM
Blizzarc
Blizzarc - avatar
+ 1
I am not having much luck finding a concrete answer online, but here are my thoughts: ++ is a unary operator. Since it works with (++x)++ it seems like an order of operations deal, but notice you cannot do ++(x++) either. Being a unary operator may explain why ++x++ does not work, but that doesn't explain ++(x++). If anyone has a better answer, please chime in as I would like to know the exact reason.
19th Nov 2016, 10:15 PM
scott johnson
scott johnson - avatar