Does your compiler get this program right?

Chris Torek chris at mimsy.UUCP
Thu Nov 24 13:41:12 AEST 1988


>In article <2298 at cbnews.ATT.COM> lvc at 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 at cs.utexas.edu> meyering at 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 at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list