Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!husc6!cmcl2!rutgers!rochester!crowl From: crowl@cs.rochester.edu (Lawrence Crowl) Newsgroups: comp.lang.c Subject: Re: Possible C Anomaly Message-ID: <2174@sol.ARPA> Date: Sat, 12-Sep-87 11:22:11 EDT Article-I.D.: sol.2174 Posted: Sat Sep 12 11:22:11 1987 Date-Received: Sun, 13-Sep-87 09:43:17 EDT References: <9236@brl-adm.ARPA> Reply-To: crowl@cs.rochester.edu (Lawrence Crowl) Organization: U of Rochester, CS Dept, Rochester, NY Lines: 28 In article <9236@brl-adm.ARPA> gamma@EDN-UNIX.arpa (W. J. Showalter) writes: ] ]/* Example #1 */ k = (k > 1) ? k-- : 1; ] ]/* Example #2 */ if (k > 1) k = k--; ] else k = 1; ] ]The problem is is that the two examples behave differently. In the first ]example k does not change values. It remains equal to 10 indefinitely. ] ]In the second example k does change like one would expect. ] ]I generated assembler listings for the two examples and discovered that ]example 1 makes used of an interim register to house the value of k ]BEFORE decrementing. It eventually moves this value back to k, replacing ]the decremented value with the original. The order of argument evaluation within expressions is undefined in C. The order of expression evaluation only matters when the expression has side effects on other parts of the expression, as yours does. Because of the undefined order, the compiler may choose to execute either k = k or k-- first. In the first example, it decrements k first and then assigns the old value of k to k. In the second example, it assigns the old value of k to k and then decrements k. In short, the code is wrong, not the compilers. -- Lawrence Crowl 716-275-9499 University of Rochester crowl@cs.rochester.arpa Computer Science Department ...!{allegra,decvax,seismo}!rochester!crowl Rochester, New York, 14627