gpt4 book ai didi

c - 为什么负长值大于正无符号长值?

转载 作者:行者123 更新时间:2023-12-02 08:08:08 25 4
gpt4 key购买 nike

示例代码:

long num1 = -1;
unsigned long num2 = 1;

if (num1 > num2)
printf("Num1 is greater\n");
else
printf("Num2 is greater\n");

为什么这会将 num1 > num2 评估为 true 而不是 false?

最佳答案

这是 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.

这正是您的示例中发生的情况:longunsigned 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 的原因。

关于c - 为什么负长值大于正无符号长值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49593880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com