interesting program
Dave Burton
daveb at laidbak.UUCP
Sun Jan 31 07:00:15 AEST 1988
In article <19 at berick.UUCP> jeffl at berick.UUCP (Jeff Lawhorn) writes:
>What does the following program print? (I know of at least one
>program that prints the wrong answer).
>
>main()
>{
> int k = 4;
> k = k++;
> printf("and the answer is %d\n", k);
> exit(0);
>}
Ambiguity warning:
According to K&R, App A, page 187:
"When the postfix ++ is applied to an lvalue the result is the value of the
object referred to by the lvalue. After the result is noted, the object is
incremented in the same manner as for the prefix ++ operator."
The ambiguous word here is "noted".
This text does not state when assignment is performed.
"Normal":
movl #4,-4(a6) | k = 4
addql #1,-4(a6) | k = k++
However, the compiler could note the result, then produce code accordingly:
movl #4,-4(a6) | k = 4
movl -8(a6),-4(a6) | [tmp = k] noted
addql #1,-4(a6) | k++ incremented
movl -4(a6),-8(a6) | k = tmp assignment
I think the result is arguably 5, but acknowledge
a result of 4 *could* be considered correct.
Flames to /dev/null, corrections to /dev/lp.
--
--------------------"Well, it looked good when I wrote it"---------------------
Verbal: Dave Burton Net: ...!ihnp4!laidbak!daveb
V-MAIL: (312) 505-9100 x325 USSnail: 1901 N. Naper Blvd.
#include <disclaimer.h> Naperville, IL 60540
More information about the Comp.lang.c
mailing list