Lobste.rs

C++ float-to-int conversion can be undefined behavior

C++ Sorting Pitfalls, UB & Type Conversion Explained - ACCU 2025 ...

Converting a float to an int in C++ is undefined behavior when the truncated float does not fit into the destination integer. C++ makes it easy to do this accidentally. Much code gets this wrong.void foo(float f) { int i0 = f; int i1 = int(f); int i2 = static_cast<int>(f); } This code does not generate any warnings, not even with -Wall and -Wextra. -Wconversion only warns about the implicit conversion. Yet each of the three conversions is undefined behavior for some inputs.Cppreference’s implicit conversion page, section Floating-integral conversions, states:A prvalue of floating-point type can be converted to a prvalue of any integer type. The fractional part is truncated, that is, the fractional part is discarded. If the value…

Continue reading at Lobste.rs kttnr.net
Advertisement