Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int to float conversion produces a warning?

It's surprising for me to see that even when the value can be converted, an int to float conversion always give a warning. Why is this?

int i = 0;
float f = 0; // warning here

// I thought this was an implicit conversion,
// meaning it is convertible with no warnings.
f = i;      // another warning here

The warning is:

warning C4244: '=' : conversion from 'int' to 'float', possible loss of data
like image 500
user103214 Avatar asked Oct 15 '11 01:10

user103214


1 Answers

I answered a similar question here:

Why does GCC warn against this implicit conversion?

The reason is that an int needs to be rounded when it is casted into a float because float cannot contain all the precision of an int in this case.

In your case, a float only has about 24 bits of precision. While an int has 32 bits of precision, therefore, some precision is loss by this cast, hence the warning.

like image 182
Mysticial Avatar answered Sep 18 '22 13:09

Mysticial