but this code always gives the same result..
Accessing a variable more than once between sequence points where one of those accesses changes the variables value is undefined behaviour (as defined by the standard).
A program exhibiting undefined behaviour may do anything including but not limited to
- Exit without explanation
- Produce some sort of exception
- Appear to operate correctly
- Operate correctly the whole time you are testing it and only go wrong the first time it is critically important that it works
- Format your hard drive
- Make demons fly out of your nose
The compiler is under
no constraints with the code it produces once undefined behaviour is invoked.
Trying to determine the output of a program exhibiting undefined behaviour is pointless because it is under no constraint to stick to whatever assumptions you have made while making that determination.
Your only real solution is to
not write code that exhibits undefined behaviour.
I am beginning to feel like a scratched record on the subject a quick forum search would have thrown up several recent threads on this very subject.