Interview Questions

Under my compiler...

C Interview Questions and Answers


(Continued from previous question...)

Under my compiler...

Q: Under my compiler, the code
int i = 7;
printf("%d\n", i++ * i++);

prints 49. Regardless of the order of evaluation, shouldn't it print 56?

A: It's true that the postincrement and postdecrement operators ++ and -- perform their operations after yielding the former value. What's often misunderstood are the implications and precise definition of the word ``after.'' It is not guaranteed that an increment or decrement 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 later.

The behavior of code which contains multiple, ambiguous side effects has always been undefined. (Loosely speaking, by ``multiple, ambiguous side effects'' we mean any combination of increment, decrement, and assignment operators (++, --, =, +=, -=, etc.) in a single expression which causes the same object either to be modified twice or modified and then inspected. This is a rough definition) Don't even try to find out how your compiler implements such things, let alone write code which depends on them (contrary to the ill-advised exercises in many C textbooks); as Kernighan and Ritchie wisely point out, ``if you don't know how they are done on various machines, that innocence may help to protect you.''

(Continued on next question...)

Other Interview Questions