Path: utzoo!mnetor!uunet!rlgvax!jesse From: jesse@rlgvax.UUCP (Jesse Barber) Newsgroups: comp.lang.c Subject: Re: interesting program Message-ID: <825@rlgvax.UUCP> Date: 4 Feb 88 00:52:02 GMT References: <19@berick.UUCP> Organization: Computer Consoles Inc, Reston VA Lines: 44 Summary: order of evaluation In article <19@berick.UUCP>, jeffl@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