Compiling the following code:
double getDouble()
{
double value = 2147483649.0;
return value;
}
int main()
{
printf("INT_MAX: %u\n", INT_MAX);
printf("UINT_MAX: %u\n", UINT_MAX);
printf("Double value: %f\n", getDouble());
printf("Direct cast value: %u\n", (unsigned int) getDouble());
double d = getDouble();
printf("Indirect cast value: %u\n", (unsigned int) d);
return 0;
}
Outputs (MSVC x86):
INT_MAX: 2147483647
UINT_MAX: 4294967295
Double value: 2147483649.000000
Direct cast value: 2147483648
Indirect cast value: 2147483649
Outputs (MSVC x64):
INT_MAX: 2147483647
UINT_MAX: 4294967295
Double value: 2147483649.000000
Direct cast value: 2147483649
Indirect cast value: 2147483649
In Microsoft documentation there is no mention to signed integer max value in conversions from double
to unsigned int
.
All values above INT_MAX
are being truncated to 2147483648
when it is the return of a function.
I'm using Visual Studio 2019 to build the program. This doesn't happen on gcc.
Am I doing someting wrong? Is there a safe way to convert double
to unsigned int
?