Path: utzoo!attcan!uunet!husc6!mailrus!ncar!tank!mimsy!chris From: chris@mimsy.UUCP (Chris Torek) Newsgroups: comp.lang.c Subject: Re: Does your compiler get this program right? Keywords: float, increment Message-ID: <14714@mimsy.UUCP> Date: 24 Nov 88 03:41:12 GMT References: <2298@cbnews.ATT.COM> <4082@cs.utexas.edu> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 49 >In article <2298@cbnews.ATT.COM> lvc@cbnews.ATT.COM >(Lawrence V. Cipriani) writes: >>A friend of mine found a bug in his C compiler. ... [f and g are both pointers to float] >>*f++ += *g++; /* miscompiled line */ [f winds up being incremented twice] In article <4082@cs.utexas.edu> meyering@cs.utexas.edu (Jim Meyering) writes: >It's not a bug. Ah, but it is. >The standard does not specify the order of evaluation for such >statements. Please read the standard (which standard, anyway?) before making such statements. The operation `a += b' is semantically equivalent to the operation `a = a + b', with the exception that the left hand side is evaluated exactly once (rather than exactly twice). Evaluating `*f++' once increments `f' by one. The lvalue produced by this evaluation (i.e., the original *f) is converted to an rvalue, has the right hand side added, and the result is stored in that same lvalue (i.e., the original *f). At some time during this process, f is incremented. The increment is to have finished by the next sequence point (dpANS). >that gave the "correct" results for your code, when I replaced >that statement by [*f += *g++; f++;] >I found that the size of the object code was actually reduced. >Chalk one up for readability *and* efficiency. That merely indicates that the compiler used is not clever enough. Unless `f' is declared volatile, the two statements are equivalent. It is not clear to me that the latter version has any advantage in readability. (Incidentally, the bug relates to PCC's practise of assuming that x op= y can be done with one instruction, which is false for straightforward implementations of floating op= operators. This assumption is in a machine-dependent part of the compiler, where it can be circumvented if necessary. The 4.3BSD-tahoe pcc gets it right, even to the extent of using `addf2 (rF)+,(rG)+' if the pointers are in registers and the compiler is invoked with the `-f' [allow single precision floating point] flag.) -- In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163) Domain: chris@mimsy.umd.edu Path: uunet!mimsy!chris