Data type promotions during arithmetic operations: -1 < (unsinged int) 1 == false

牧云@^-^@ 提交于 2019-11-28 09:16:42

The rules are as follows:

6.3.1.8 Usual arithmetic conversions

...

Otherwise, the integer promotions are performed on both operands. Then the following rules are applied to the promoted operands:

  1. If both operands have the same type, then no further conversion is needed.
  2. Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.
  3. Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.
  4. Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.
  5. Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.

The rules then work as follows:

  • -1 < (unsigned char) 1

First both operands are converted to ints (because an int can represent all values of unsigned char). Then the comparison is made on these signed types. Rule 1 is then used. The comparison succeeds.

  • -1 < (unsigned int) 1

An int cannot represent all the values of an unsigned int so rule 3 is used and the signed integer is converted to an unsigned integer (UINT_MAX - 1). The comparison now fails.

This is due to integer promotions. Both arguments can be represented as an int, so they are converted to an int.

ISO C 6.3.1.1, paragraph 2:

If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions.48) All other types are unchanged by the integer promotions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!