Manon
Manon

Reputation: 169

Is a conversion from a double to a float always potentially invoking undefined behaviour?

Here is the relevant part of the standard (6.3.1.5.2 Real floating types) of C99 :

When a double is demoted to float, a long double is demoted to double or float, or a value being represented in greater precision and range than required by its semantic type (see 6.3.1.8) is explicitly converted (including to its own type), if the value being converted can be represented exactly in the new type, it is unchanged. If the value being converted is in the range of values that can be represented but cannot be represented exactly, the result is either the nearest higher or nearest lower representable value, chosen in an implementation-defined manner. If the value being converted is outside the range of values that can be represented, the behavior is undefined.

In order to avoid undefined behavior, every time I want to convert a double to a float, I would have to manually check that the values of the double can be represented in the range of the float, correct ?

Upvotes: 3

Views: 960

Answers (1)

Steve Summit
Steve Summit

Reputation: 47942

Short answer: Yes.

If you are converting double to float, and if you have no idea what the values might be, then for well-defined behavior you will want to check the range of each value first, and take appropriate action if a value is too large to fit in type float.

You'd want to do it this way even if the result in the overflow case weren't undefined, because whatever the overflow result was, it wouldn't necessarily be what you wanted. (Depending on the application, you probably want to report an error back to your user/caller.)

Upvotes: 1

Related Questions