C++ Logo


Advanced search

Out-of-range floating-point conversion behavior

From: Myria <myriachan_at_[hidden]>
Date: Tue, 4 Jun 2019 12:59:33 -0700
Something came up in a Twitter thread that was interesting. The
following is considered undefined behavior by Clang++ and throws a
runtime error with -fsanitize=undefined.


int main() {
    double d2=DBL_MAX;
    float f=d2;

Clang++ considers this undefined behavior because of [conv.double]:

"A prvalue of floating-point type can be converted to a prvalue of
another floating-point type.
If the source value can be exactly represented in the destination
type, the result of the conversion is that exact representation. If
the source value is between two adjacent destination values, the
result of the conversion is an implementation-defined choice of either
of those values.
Otherwise, the behavior is undefined."

But "the source value is between two adjacent destination values" is
true; namely FLT_MAX and +infinity. With this interpretation of the
wording, it seems like the result ought to be an
implementation-defined choice between FLT_MAX and +infinity. (I would
argue that because std::numeric_limits<float>::is_iec559() is true in
this implementation, its "choice" must be what IEC 559 / IEEE 754
mandates in this situation.)

What is the correct interpretation here?


Received on 2019-06-04 15:01:31