如何在 C 中比较无符号整数和文字?

How does an unsigned integer and literal get compared in C?

我正在进行以下比较:

uint32_t value = 1000;

if(value < 100)
{
  // do something
}

在这种情况下,什么被转换成什么? 'value' 是否被转换为整数? 100 会转换为整数还是无符号整数?

如果两个整数表达式具有与示例中相同的等级,前提是类型 uint32_t 是类型 unsigned int 的别名,则有符号类型将转换为无符号类型。也就是说,将类型为 signed int 的整数文字 100 转换为类型 unsigned int。

来自 C 标准(6.3.1.1 布尔值、字符和整数)

— The rank of any unsigned integer type shall equal the rank of the corresponding signed integer type, if any.

与(6.3.1.8 常用算术转换)

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

首先,所有数字常量都有一个类型。在常量 100 的情况下,因为它是十进制,没有后缀,并且可以适合 int 的范围,所以常量具有类型 int.

比较的执行方式由通常的算术转换决定。具体的,整数类型的转换规则在C standard的6.3.1.8p1节规定如下:

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

  • If both operands have the same type, then no further conversion is needed.
  • 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.
  • 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.
  • 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.
  • Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type

假设您平台上的 int 是 32 位,这使得 uint32_tunsigned int 相同,因此您使用的是有符号类型和无符号类型表达式中的大小相同。在这种情况下,上面的第三个要点适用,即值 100(具有类型 int)转换为 unsigned int,然后比较这些值。

在这种情况下,值100也在unsigned int的范围内,因此没有实际值的转换。如果它是类似 -100 的东西,则该值不在 unsigned int 的范围内,这意味着该值将被转换为在该范围内。同样,假设 32 位 int 值将是 232 - 100.