Casting and Optimization Flags

Rob Shearer Rob.Shearer@networkinference.com
Wed Dec 11 04:43:00 GMT 2002


casting floats to integers does not round; it truncates

To round, simply add 0.5 to your float.

Obviously I don't know what you're trying to do, but there look to be a
number of significant ways to improve the code you've outlined.
Explicitly casting an integer literal is never necessary; just create
the type you want: 2 may be an integer, but 2.0 is a double, 2.0f a
float, and 2.0l (that's an el, not a one) a long double. More to the
point, if all you're doing is finding the log in base 2 then that is
just the highest bit that's set and there are many much more efficient
ways to find this than going through floating point math.

> -----Original Message-----
> From: Colin Law [mailto:c.law@elec.gla.ac.uk] 
> Sent: 11 December 2002 12:24
> To: gcc-help@gcc.gnu.org
> 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.
> 
> 
> 
> 



More information about the Gcc-help mailing list