Why is −1 > sizeof(int)?

后端 未结 4 813
[愿得一人]
[愿得一人] 2020-11-30 14:41

Consider the following code:

template class StaticAssert;
template<> class StaticAssert {};
StaticAssert< (-1 < sizeof(in         


        
4条回答
  •  独厮守ぢ
    2020-11-30 15:21

    The following is how standard (ISO 14882) explains abort -1 > sizeof(int)

    Relational operator `>' is defined in 5.9 (expr.rel/2)

    The usual arithmetic conversions are performed on operands of arithmetic or enumeration type. ...

    The usual arithmetic conversions is defined in 5 (expr/9)

    ... The pattern is called the usual arithmetic conversions, which are defined as following:

    • If either operand is of type long double, ...
    • Otherwise, if either operand is dobule, ...
    • Otherwise, if either operand is float, ...
    • Otherwise, the integral promotions shall be performed on both operands.
    • ...

    The integral promotions is defined in 4.5 (conv.prom/1)

    An rvalue of type char, signed char, unsigned char, short int, or unsigned short int can be converted to an rvalue of type int if int can represent all the values of the source type; otherwise, the source rvalue can be converted to an rvalue of type unsigned int.

    The result of sizeof is defined in 5.3.3 (expr.sizeof/6)

    The result is a constant of type size_t

    size_t is defined in C standard (ISO 9899), which is unsigned integer type.

    So for -1 > sizeof(int), the > triggers usual arithmetic conversions. The usual arithmetic conversion converts -1 to unsigned int because int cannot represent all the value of size_t. -1 becomes a very large number depend on platform. So -1 > sizeof(int) is true.

提交回复
热议问题