为什么负长值大于正无符号长值?
why is a negative long value greater than a positive unsigned long value?
示例代码:
long num1 = -1;
unsigned long num2 = 1;
if (num1 > num2)
printf("Num1 is greater\n");
else
printf("Num2 is greater\n");
为什么这会评估 num1 > num2 为真而不是假?
这是 C99 标准第 6.3.1.8 节中描述的整数提升规则的结果:
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.
这正是您的示例中发生的情况:long
和 unsigned long
具有相同的等级,因此带符号的 long
被转换为 unsigned long
。
由于 -1
不能表示为无符号数,因此以下规则开始起作用:
When a value with integer type is converted to another integer type other than _Bool
, if the value can be represented by the new type, it is unchanged. 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.
因此,结果是 1- + ULONG_MAX-1
,等于 ULONG_MAX
。这就是为什么将 -1
转换为 unsigned
的结果大于 1
.
在表达式中同时使用 long
和 unsigned long
时,“longvalue is converted to
unsigned long. This results in the value -1 becoming the largest
unsigned long”值大于 1。
您正在比较两个不同数据类型的变量,即 long 和 unsigned long。
在这种情况下,在比较两个变量期间,编译器隐式类型转换变量num1到unsigned long因为无法比较不同数据类型的两个变量。
因此,num1 正在转换为 65534 [65535 - 1].
因此,您得到 Num1 更大
示例代码:
long num1 = -1;
unsigned long num2 = 1;
if (num1 > num2)
printf("Num1 is greater\n");
else
printf("Num2 is greater\n");
为什么这会评估 num1 > num2 为真而不是假?
这是 C99 标准第 6.3.1.8 节中描述的整数提升规则的结果:
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.
这正是您的示例中发生的情况:long
和 unsigned long
具有相同的等级,因此带符号的 long
被转换为 unsigned long
。
由于 -1
不能表示为无符号数,因此以下规则开始起作用:
When a value with integer type is converted to another integer type other than
_Bool
, if the value can be represented by the new type, it is unchanged. 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.
因此,结果是 1- + ULONG_MAX-1
,等于 ULONG_MAX
。这就是为什么将 -1
转换为 unsigned
的结果大于 1
.
在表达式中同时使用 long
和 unsigned long
时,“longvalue is converted to
unsigned long. This results in the value -1 becoming the largest
unsigned long”值大于 1。
您正在比较两个不同数据类型的变量,即 long 和 unsigned long。
在这种情况下,在比较两个变量期间,编译器隐式类型转换变量num1到unsigned long因为无法比较不同数据类型的两个变量。
因此,num1 正在转换为 65534 [65535 - 1].
因此,您得到 Num1 更大