This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Casting and Optimization Flags
- From: Colin Law <c dot law at elec dot gla dot ac dot uk>
- To: gcc-help at gcc dot gnu dot org
- Date: Wed, 11 Dec 2002 12:23:35 +0000
- Subject: Casting and Optimization Flags
Hello,
I am having trouble with a section of code that runs fine when compiled
with no optimization flags, however when I add optimization,flags, I get
different results.
In the middle of a for loop, and a fairly heavily recursive procedure i
has this;
double d = (std::log10(static_cast<double>(width))) /
(std::log10(static_cast<double>(2))) ;
unsigned int level = static_cast<unsigned int>(d) ;
Which will (should) always return me an integer value for my values of
width (always 2^n values). When i sprinf both d and level i can see that
the value is cast fine with no optimization, however when i compile with
-O2 or -O1, after the cast the int doesn't always match the double,
casting double 3 to an unsigned int =2 !!!
It appears that my double value is so close to an int that it is
regarded as a whole number,however during the cast the decimal values
are simpley chopped so 2.9999..... cast to unsinged int is 2. sprinf
(%.20f) tells me the value of d is 3.0000... not 2.9999...
I am unable to reprodude this problem in a trivial case which suggests
it is something i am missing in the main code, however, as i am
assigning to new variables, i cannot see where this could possible be.
If I use long double instead of double during the calculation. then
cast, I appear to get the correct results even with optimization!
Any suggestions as to what is causing this ??
I am using g++-3.2 and am compiling the above as part of a shared
library with -fPIC -Wall -O2 if thats any help.
Regards
~Colin.