0

I'm trying to understand is this undefined.

#include <iostream>
#include <limits>

int main() {
    int integer_number = std::numeric_limits<int>::max();
    std::cout << integer_number << std::endl;

    float float_number = static_cast<float>(integer_number);
    std::cout << float_number << std::endl;
    
    integer_number = static_cast<int>(float_number);
    std::cout << integer_number << std::endl;

    float_number = std::numeric_limits<float>::max();
    std::cout << float_number << std::endl;


    return 0;
}

output of a program:

2147483647
2.14748e+09
-2147483648
3.40282e+38

compiling with flags : -std=c++20 -Wall -Wpedantic -Werror -Wconversion -O0

Compiler explorer

phuclv
  • 37,963
  • 15
  • 156
  • 475
  • 4
    If I recall correctly, it is undefined behavior to assign a float to a int when the float is out of range of the int. On some platforms, the max int `2147483647` can round up to `2147483648` when stored into a float. (Because int has 32-bit precision, and float has 24-bit precision. Commonly; but it is platform dependent.) – Eljay Jun 03 '22 at 16:12
  • 1
    @Eljay when your int is 32 bits but the mantissa of a float is only 24 bits, something's gotta give. And yes that's platform dependent, but I haven't seen a non IEEE compliant float in forever. – Mark Ransom Jun 03 '22 at 16:18
  • 1
    @Eljay that's correct. Both GCC and Clang throws `runtime error: 2.14748e+09 is outside the range of representable values of type 'int'`: https://godbolt.org/z/5WMGfczbb – phuclv Jun 03 '22 at 16:20
  • @phuclv that surprises me, doing a run time check against limits would add too much overhead. I wonder how they do it? – Mark Ransom Jun 03 '22 at 16:23
  • 1
    @MarkRansom that's the [ASan/UbSan](https://en.wikipedia.org/wiki/AddressSanitizer) in [gcc](https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html), Clang and MSVC which obviously only work when you enable the feature – phuclv Jun 03 '22 at 16:25
  • @MarkRansom • I get to work with some oddball platforms, some of which don't have IEEE 754 floats. :-( I also got to work on an experimental 128-bit `int` operating system project, but it has since been abandoned (due to moving from Intel x86-64 to ARM). The sanitizers do add a nominal amount of overhead. – Eljay Jun 03 '22 at 16:25

0 Answers0