Why the behavior of double to int typecasting different in x86_64 and aarch64 during the integer overflow case?

70 Views Asked by At

I have the following sample code which I am compiling and executing on x86_64 and aarch64 platforms but ending up with different outputs.

#include <iostream>

int main()
{
    double d = 2147483649;
    int i = d;

    std::cout << i << std::endl;

    return 0;
}

Output on x86_64: -2147483648 Output on aarch64: 2147483647

Why there is a difference in output on both the architectures. Is there any option I need to pass to the compiler in case of aarch64 to make the behavior consistent to that of x86_64?

I tried compiling the code as following "g++ a.cpp -o a.o" on both the architectures. And I am expecting to return the same value of "i" on both the architectures.

1

There are 1 best solutions below

0
ChrisMM On

Such a conversion is undefined behaviour, and thus, the compiler can do whatever it wants.

Per [conv.fpint],

A prvalue of a floating-point type can be converted to a prvalue 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.