(float) casting doesn't work

I 'by trying this simple code. It shows the first 10 integers that cannot be represented in floats:

int main(){
  int i, cont=0;
  float f;
  double di, df;
  for(i=10000000, f=i; i<INT_MAX; i++, f=i, df=f, di=((float)i)){
    if(i!=f){
      printf("i=%d   f=%.2f   df=%.2lf   di=%.2lf\n", i, f, df, di);
      if(cont++==10) return 0;
    }
  }
  return 1;
}

      

di is a double variable, but I am setting it to (float) i, so it should be equal to df, but it is not.

For example, the number 16777217 is represented as 16777216 by f and df, but di is still 16777217, ignoring the (float) cast.

How is this possible?

** I am using this: gcc (Ubuntu 4.4.3-4ubuntu5) 4.4.3

+3


source to share


2 answers


Corresponding to your question is question 6.3.1.8: C99 standard :

The values ​​of floating operands and results of a floating expression can be represented with greater precision and range than the type required; types don't change this way.

and in particular footnote 52:



Cast and assignment operators still need to perform their specified conversions as described in 6.3.1.4 and 6.3.1.5.

Reading the footnote, I would say that you have identified a bug in your compiler.

You may have identified two bugs in your compiler: the comparison i!=f

is done between floats (see promotion rules on the same standard page), so it must always be false. While in this latter case I think the compiler might be allowed to use a larger type for comparison on 6.3.1.8-2, it is possible that the comparison is equivalent (double)i!=(double)f

and therefore sometimes true. Clause 6.3.1.8-2 is the paragraph in the standard that I hate the most, and I'm still trying to figure out strict alias.

+2


source


This post explains what's going on:

http://www.exploringbinary.com/when-floats-dont-behave-like-floats/



As an additional estimate, the precision can be stored on the machine for different evaluations of the expression, which makes the floats unequal.

+2


source







All Articles