Variables are evaluated by the compiler before relationships. The compiler is free to evaluate the variables in any order. Therefore, different compilers will produce different results.
You cannot change a variable more than once in a statement.
Your expression tries to change i more than once within the same statement. The C Standard says trying to modify the value of a variable more than once in the same statement is undefined behavior.
The C Standard does not impose any limitation on what happens when undefined behavior occurs.
You may get a build error.
You may get a run-time error.
You may get a result that makes some sort of sense.
You may get a result that makes no sense at all.
You may get a different result each time.
Your hard drive may be reformatted.
You may get a speeding ticket later that day.
Glaciers may advance.
Global air and ocean temperatures may rise enough to change the climate.
The simplest trick is to calculate the prefix operators first and then put the net value in the expression.
1. i++ + i++
No prefix operator. so, i=5
exp=5+5=10, i=5+1+1=7
2. i-- - i++
No prefix operator. so, i=5
exp=5-5=0, i=5-1+1=5
3. ++i - --i
net value of i= 5+1-1=5
exp=5-5=0, i=5+1-1=5
4. --i + i--
net value of i= 5-1=4
exp=4+4=8, i=5-1-1=3
@HSharma1729, what you say may seem plausible but I assure you there are compilers around that won't provide the results you expect. I wouldn't be surprised if there weren't compilers out there that give different answers depending on what level of optimization is selected.
Comment