interesting program
Jesse Barber
jesse at rlgvax.UUCP
Thu Feb 4 10:52:02 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);
> }
What the program prints depends on the compiler used. I used two compilers
msc 4.0 and CCI's 6/32 compiler.
msc printed 4
cci printed 5
However, neither of these compilers is wrong. Remember the old adage
" It's a poor workman that blames his tools"
On page 49 of K&R copyright 1978 it states
"C, like most languages, does not specify in what order the operands of
an operator are evaluted"
The two results I got are because the two compilers evaluated the operands
of the "=" in a different order.
msc:
tmp = k; /* evaulate k */
k = k + 1; /* evaluate k++ */
k = tmp; /* evaluate = */
cci:
k = k; /* evaluate = */
k = k + 1; /* evaluat k++ */
As a matter of fact, K&R use the increment operator to demonstrate this
kind of problem.
Notice that in code which does not depend on the order of evaluation
both compilers produce "correct" responses.
--
..!seismo!rlgvax!jesse ( Jesse @ C.C.I. Reston, Va.)
Have brain, will travel
More information about the Comp.lang.c
mailing list