Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.2 9/18/84; site watdaisy.UUCP Path: utzoo!watmath!watdaisy!ndiamond From: ndiamond@watdaisy.UUCP (Norman Diamond) Newsgroups: net.lang.c Subject: Re: C question Message-ID: <7181@watdaisy.UUCP> Date: Mon, 8-Apr-85 13:05:17 EST Article-I.D.: watdaisy.7181 Posted: Mon Apr 8 13:05:17 1985 Date-Received: Tue, 9-Apr-85 01:45:07 EST References: <5272@tektronix.UUCP> Organization: U of Waterloo, Ontario Lines: 42 > 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@waterloo.csnet ARPA: ndiamond%watdaisy%waterloo.csnet@csnet-relay.arpa "Opinions are those of the keyboard, and do not reflect on me or higher-ups."