为什么控制转到 else 块进行此条件检查?

Why the control goes to the else block for this conditional check?

我想知道为什么它只执行else语句

代码如下:

#include<stdio.h>
int main()
{
    unsigned int a = 100;
    int b = -100;
    if(a > b)
    {
        print("Obviously 100 is Bigger than -100!\n");
    }
    else
        print("Something Unexpected has Happened\n");
}

此声明

  if(a>b)

涉及有符号整数和无符号整数之间的运算(比较),按照提升规则,有符号整数会被提升为无符号整数并产生一个巨大的无符号值:例如在32-的环境中位整数,该值为 4294967196 (232 - 100).

因此,条件看起来像

if (100 > 4294967196)

并将评估为 false,确保执行 else 块中的代码。

发生这种情况是因为值 -100 正在转换为一个较大的正值。

您看到的是常规算术转换的结果。当在表达式中使用相同等级的有符号整数值和无符号整数值(intunsigned int)时,有符号值将转换为无符号值。

这些转换在 C standard 的第 6.3.1.8p1 节中有详细说明:

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.

突出显示的段落适用于这种情况。至于实际转换是如何发生的,在第 6.3.1.3p2 节中有详细说明:

Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

所以假设一个unsigned int的大小是32位,没有填充字节,它可以容纳的最大值是4294967295。这意味着值-100被转换为值4294967196。这意味着比较实际执行的是 100 > 4294967295,这是错误的,因此执行语句的 else 部分。