[NTLUG:Discuss] The wrong computation example from the newsgroup
Steve Baker
sjbaker1 at airmail.net
Sun Mar 18 13:15:10 CST 2001
Christopher Browne wrote:
> % hostname
> chvatal
> % arch
> i686
> % gcc ctest.c -o ctest
> % ./ctst
> 10=9
> % gcc ctest.c -O2 -o ctest
> % ./ctst
> 10=10
> It's fairly surprising that the compiler evaluates the value
> differently from the computation in the compiled program, and the
> reasons for that are well worth investigating. But it should come as
> no shock to the gentle reader for a floating point approximation to 10
> to be either slightly larger, or slightly smaller than 10.
I'm guessing that the '-O2' option "worked" because it spotted that
the variables were not changed between initialisation and the printf
and therefore could be evaluated at compile time. Almost any change
to the source code could 'disturb' that delicate situation and prevent
the compiler from spotting the optimisation.
The probable reason for the difference between compile-time evaluation
and runtime evaluation is in the order of operations. The compiler
probably builds an expression-tree and evaluates it exactly as written
where the runtime code it generates might well multiply 'a' by 0.3
and *then* divide by 'b' - or something like that.
The differing results in the Alpha are similarly unsuprising - the
compiler may well need to change the order of operations differently
in order to make optimal code with the Alpha's machine code instruction
set versus the Pentium's instruction set.
Like I said before - it's just as likely to depend on the phase of the
moon.
--
Steve Baker HomeEmail: <sjbaker1 at airmail.net>
WorkEmail: <sjbaker at link.com>
HomePage : http://web2.airmail.net/sjbaker1
Projects : http://plib.sourceforge.net
http://tuxaqfh.sourceforge.net
http://tuxkart.sourceforge.net
http://prettypoly.sourceforge.net
http://freeglut.sourceforge.net
More information about the Discuss
mailing list