prev up next   top/contents search

comp.lang.c FAQ list · Question 3.2

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; see question 3.8). 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; see question 3.8 for a precise one, question 3.11 for a simpler one, and question 11.33 for the meaning of ``undefined.'') 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.''

References: K&R1 Sec. 2.12 p. 50
K&R2 Sec. 2.12 p. 54
ISO Sec. 6.3
H&S Sec. 7.12 pp. 227-9
CT&P Sec. 3.7 p. 47
PCS Sec. 9.5 pp. 120-1

prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North