Under my compiler, the code int i = 7; printf(“%d “, i++ * i++); prints 49. Regardless of the order of evaluation, shouldn it print 56?
Although the postincrement and postdecrement operators ++ and — perform the operations after yielding the former value, the implication of “after” is often misunderstood. It is _not_ guaranteed that the operation is performed immediately after giving up the previous value and before any other part of the expression is evaluated. It is merely guaranteed that the update will be performed sometime before the expression is considered “finished” (before the next “sequence point,” in ANSI C’s terminology). In the example, the compiler chose to multiply the previous value by itself and to perform both increments afterwards. The behavior of code which contains multiple, ambiguous side effects has always been undefined. Don’t even try to find out how your compiler implements such things (contrary to the ill- advised exercises in many C textbooks); as K&R wisely point out, “if you don’t know _how_ they are done on various machines, that innocence may help to protect you.” References: K&R I Sec.
Related Questions
- Under my compiler, the code int i = 7; printf("%d ", i++ * i++); prints 49. Regardless of the order of evaluation, shouldn it print 56?
- I get compiler errors when trying to compile the provided code without changing anything. What is wrong?
- How do I code the SELECT/ASSIGN statements for the MVT COBOL compiler?