Freigeben über


Float to int conversion may return different values.

Hi there! Recently I remembered that I had an MSDN blog also which I haven't updated since ages! Let me add an interesting issue which I saw recently:

The following code results in different output when built and run from Visual Studio 2003 and Visual Studio 2008:

Code

=====================

#include <stdio.h>

void main()
{

float SinglePrecisionValue;
long result;

SinglePrecisionValue = 3.40282535e+37;

result = (long)SinglePrecisionValue ;

printf("%ld\n", result);

}

Output

=========================
1. Result from VS2003: 0
2. Result from VS2008: -2147483648

So what is happening here? The code tries to convert a float value to long. So why are we getting different values from different compilers?

The C++ Standard says:

An rvalue of a floating point type can be converted to an rvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type.

Results are incompatible only in cases where program behavior is undefined according to C/C++ Standards. The conversion from Float to int is backward compatible till everything is according to the C++ standards. The problem happens only when truncated value cannot be represented in the destination type. This is the case here. So both the results are expected. We cannot expect undefined behavior to result in same output from two different compilers!

Comments