What happens if a negative floating point value is converted into a value of unsigned integral type? Standard quotes would be appreciated. The problem I'm facing is conversion into values of unsigned integral types from a variant class, that contains an object of floating-point type.
EXAMPLE:
unsigned i = -.1;
You simply cannot assign a negative value to an object of an unsigned type. Any such value will be converted to the unsigned type before it's assigned, and the result will always be >= 0.
The representation in 2s complement is not mandated by the standard but the algorithm to convert to unsigned is: "the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the newtype until the value is in the range of the newtype."
Attempts to assign a negative float value to an unsigned int or an unsigned short variable and compiled with IBM C/C++ compiler (xlc, xlC or xlc++) on AIX, results an undefined value stored in the unsigned int variable.
Floating point numbers can be positive or negative.
In case the negative value is -1.0 or lower, it invokes undefined behavior since the integral part then cannot be represented by an unsigned number. Otherwise, (as in the case of -0.1), if it can be represented by an integer type, it is well-defined behavior. See the C11 standard, ISO 9899:2011:
6.3.1.4
When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined. 61)
And then there is a non-normative foot note explaining the above text:
61) The remaindering operation performed when a value of integer type is converted to unsigned type need not be performed when a value of real floating type is converted to unsigned type. Thus, the range of portable real floating values is (−1, Utype_MAX+1).
ISO/IEC 9899:1999 (C99) contains exactly the same text.
It is undefined behaviour in C99 if the floating point number is less than or equal to -1.0. If it's in the range (-1.0, 0.0), the resulting value will be 0.
From C99, §6.3.1.4, paragraph 1
When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined
Footnote 50 clarifies the behaviour for the (-1.0, 0.0) range.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With