What does the C ++ standard say about casting a value of a type that is outside the range of the target type?

I recently had to do some data type conversions from floatup to a 16-bit integer. In fact, my code boils down to the following

float f_val = 99999.0;
short int si_val = static_cast<short int>(f_val);

// si_val is now -32768

This input value was a problem, and in my code I neglected to check the limits of the float value so that I could see my error, but it made me think about the exact rules of the language when you need to make such a clumsy cast. I was a little surprised to find that the actor's value was -32768. Also, this is the value that I get whenever the float value exceeds the limits of a 16-bit integer. I searched for this, but found an amazing lack of detailed information about it. The best I could find was: cplusplus.com

Converting to int from some smaller integer type or doubling from float is known as promotion, and is guaranteed to have the same value in the destination type. Other conversions between arithmetic types may not always represent the same value, namely:

If the conversion is from a floating-point type to an integer type, the value 
is truncated (the decimal part is removed).
The conversions from/to bool consider false equivalent to zero (for numeric 
types) and to null pointer (for pointer types); and true equivalent to all 
other values.
Otherwise, when the destination type cannot represent the value, the conversion 
is valid between numerical types, but the value is
implementation-specific (and may not be portable).

This assumption that the results are defined does not surprise me, but I heard that cplusplus.com is not always reliable.

Finally, when performing the same actor with a 32-bit integer up to a 16-bit integer (again with an outisde value from the 16-bit range), I saw results clearly indicating integer overflows. Although I was not surprised by this, he added to my confusion due to inconsistency with the cast of the floattype.

++, ++ , , ? g++ 4.6.3.

+4
1

, , . , , .

4.9 [conv.fpint]

1 prvalue . ; .. . undefined, . [. bool, . 4.12. - ]

, , - .

+8

All Articles