C++ float-to-int conversion can be undefined behavior
7 hours ago
- Converting a float to an int in C++ is undefined behavior when the truncated float does not fit into the destination integer.
- C++ allows implicit and explicit float-to-int conversions without warnings, even with -Wall and -Wextra.
- Microsoft's Guidelines Support Library (GSL) provides gsl::narrow for safe narrowing, but it uses undefined behavior internally for float-to-int conversions.
- The undefined behavior often works on current hardware (e.g., x86 CVTTSS2SI maps unrepresentable inputs to INT_MIN), but it's not portable or safe.
- The correct fix is to perform bounds checking before casting, as demonstrated in a proof-of-concept library based on Rust's saturating approach.
- Clang and GCC's Undefined Behavior Sanitizer (UBSan) with -fsanitize=float-cast-overflow can detect such undefined behavior.