C question
Norman Diamond
ndiamond at watdaisy.UUCP
Tue Apr 9 04:05:17 AEST 1985
> An inexperienced C programmer wrote a program containing the following:
>
> x = x++;
>
> Assuming that x originally had the value 5, what should the value be after
> execution of the above expression ?
>
> In favor of 5:
> According to the operator precedence table in K&R on page 49, the ++
> operator has higher precedence than the = operator. Hence the sequence of
> operations should be:
> evaluate x (value == 5)
> increment x (x now == 6)
> assign the computed value to x (x now == 5 again)
>
> In favor of 6:
> In K&R on page 42, the text says: "But the expression ++n increments n
> *before* using its value, while n++ increments n *after* its value has been
> used." Hence, the sequence of operations should be:
> evaluate x (value == 5)
> assign the computed value to x (x still == 5)
> increment x (x now == 6)
The language definition doesn't say, and the construct is ambiguous
(semantically ambiguous, not syntactically). Therefore all four compilers
are correct (for this statement anyway) and the program is incorrect.
Actually I am usually quick to catch ambiguities (roughly the same as
finding counter-examples to false theorems), but never would have thought
of that second interpretation. Yes the increment occurs after binding
the old value, but in this particular case, even I never thought of other
operations sliding in between. It's rather astounding.
--
Norman Diamond
UUCP: {decvax|utzoo|ihnp4|allegra}!watmath!watdaisy!ndiamond
CSNET: ndiamond%watdaisy at waterloo.csnet
ARPA: ndiamond%watdaisy%waterloo.csnet at csnet-relay.arpa
"Opinions are those of the keyboard, and do not reflect on me or higher-ups."
More information about the Comp.lang.c
mailing list