Answer by Aparajita Raychaudhury:
Oh dear! Indian teachers will never learn not to set this question. Ironically enough I have failed to explain to them why this a++ + ++a bullshit is totally nonsensical. They just love this question.
Like the only other correct answer on the page mentions, the behaviour is undefined. Which means a compiler can do exactly as it pleases when asked to convert this statement. It can convert in such a way that you get 5 or 6 or 99 or it could create code to wipe off your entire hard drive. It would still be a perfectly valid C compiler.
I wrote a pretty detailed explanation somewhere else on Quora, but unfortunately I can’t find it anymore.
C has a concept known as ‘sequence points’. Sequence points are basically a point in your code where the compiler guarantees to have finished off all evalutations. For example, a semi-colon at the end of a statement is a sequence point. So a C compiler guarantees that before it moves to the next code after a semi-colon, it will finish doing everything before the semicolon. So when you write a=b+c; printf(“%d”, a);, you know a will be printed as whatever is b+c, because there is a sequence point before printf, and hence the compiler guaranteed to finish the calculation before starting to print. But what order the C compiler executes statements within a sequence point can not be guaranteed. For example, if you write a=b++ + c++; you can’t guarantee whether b will be incremented first or c. In most cases it doesn’t matter, because no one cares what order it is evaluated in. But in some cases it does.
Now to come to undefined behaviour. The C language standard says that the value of a variable can change at most once within a single sequence point. If a code attempts to change a variable’s value more than once within the same sequence point, it is undefined behaviour. Which means the C compiler can do exactly whatever it wants. It can even format your root drive. Anything is fine.
So when you do something like a++ + ++a, you are attempting to change the value of variable a twice within the same sequence point. This is not allowed. Since you defied the holy laws of C, now the compiler can do anything it wants. And apparently it does. Which is why in your case it says 6, whereas other people using other compilers (or other versions of your compiler) get 5. It can even say 99. Or -99. Anything is correct. Because you broke the Holy Commandment. Which is why Sergey says that the answers you get is non-sensical. It could be just some random value the compiler decided to spit out on the spur of the moment.
And the worst part is, a single piece of undefined code makes the entire program undefined. The compiler can do absolutely anything it pleases, because, yeah, you know, you broke the law.
Good luck getting your teachers to even recognise the law though.