Apparently, the arguments of printf are evaluated in reverse order (i++, then ++i), so:
i++ is a postincrement, so it evaluates to i (or -1) before it increments i, making it 0, so the second thing that gets printed is -1.
++i is a preincrement, so it first increments i, making it 1, then evaluates to i, making it 1, which is the first thing printed out.
From this, you can probably tell that, in general, it's not a good idea to use i++ and ++i in a complex operation where you need i more than once because it can be difficult to predict the order it will be evaluated in.
What you did was invoking an undefined behavior - actually two here:
1. 'i' is being modifying twice within a sequence point.
Both pre- and post operator have side effects on the variable ¡V the value is being incremented or decremented and yield the result before or after the changes. What is not clear is the implication of ¡§before¡¨ or ¡§after¡¨. The standard only guaranteed that the side effects are settled before the beginning of the next sequence point. Other than that, the compiler can implement anything it deems appropriate.
2. The order of argument evaluation in a function call is implementation specific.
The function call itself has two sequence points. One just after evaluating all function argument and one before the function returns. Therefore there is again no guaranty the order of evaluation of the function arguments. It can be from left to right, right to left or any order the compiler/optimizer deems appropriate.
Once an undefined behavior is invoked, the entire statement becomes undefined. There is no way to justify the results. The best deduction you can reason is how the codes are being generated by the compiler. And this cannot be guarantied to be consistent ¡V The same compiler can generate totally different codes (and thus a different result) if different compiler options (like optimization) being used.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.