I am confused as to this part of exemplary code:
float f = 3.01;
int i;
- Case 1:
i = f * 100; // i == 300 - Case 2:
i = f *= 100; // i == 301
I’ve no idea why in first case the decimal part gets “lost”.
I’ve also tried:
(double) f * 100
f * 100.0
Then I tried volatile and flags to gcc that turn off all optimization.
The result is still the same.
Can somebody explain to me why does the first case behave so? Thank you.
The issue is in type conversion:
is equivalent to
And the difference with second case is that tmp is
double! And yes, there is a case, where double is “less precise”To illustrate this, I wrote the follwing program:
Edit:
On my system I get same result for my
gcc 4.6.1andcl 16.00(MS VS 10):Edit2
Found, that enabling optimization
-O2eliminates issue. This explains difference with IDEONE.Here is another code:
And its assembly with
-O0We can see only one explicit conversion to single precision instruction (
fspts). This conforms my guess, that temporary evaluates fromdouble, notfloat.And with
-O2assembly is pretty simple:And at last
If we disable optimization of evaluting, IDEONE compiler reproduce behavior too: