What does “representable” mean in C11?

前端 未结 3 1050
自闭症患者
自闭症患者 2020-12-06 18:48

According to C11 WG14 draft version N1570:

The header declares several functions useful for classifying and mapping cha

3条回答
  •  情书的邮戳
    2020-12-06 18:58

    What does representable in a type mean?

    Re-formulated, a type is a convention for what the underlying bit-patterns mean. A value is thus representable in a type, if that type assigns some bit-pattern that meaning.

    A conversion (which might need a cast), is a mapping from a value (represented with a specific type) to a value (possibly different) represented in the target type.


    Under the given assumption (that char is signed), CHAR_MIN is certainly negative, and the text you quoted leaves no room for interpretation:
    Yes, it is undefined behavior, as unsigned char cannot represent any negative numbers.

    If that assumption did not hold, your program would be well-defined, because CHAR_MIN would be 0, a valid value for unsigned char.

    Thus, we have a case where it is implementation-defined whether the program is undefined or well-defined.


    As an aside, there is no guarantee that sizeof(int)>1 or INT_MAX >= CHAR_MAX, so int might not be able to represent all values possible for unsigned char.

    As conversions are defined to be value-preserving, a signed char can always be converted to int.
    But if it was negative, that does not change the impossibility of representing a negative value as an unsigned char. (The conversion is defined, as conversion from any integral type to any unsigned integral type is always defined, though narrowing conversions need a cast.)

提交回复
热议问题