了解 2^31 和 -2^31 整数提升
Understanding 2^31 and -2^31 integer promotion
#include <stdio.h>
int main() {
printf("sizeof(int): %zu\n", sizeof(int));
printf("%d\n", 2147483648u > -2147483648);
printf("%d\n", ((unsigned int)2147483648u) > ((int)-2147483648));
printf("%d\n", 2147483648u != -2147483648);
printf("%d\n", ((unsigned int)2147483648u) != ((int)-2147483648));
return 0;
}
此代码在 C 和 C++ 中的输出,在 cygwin64 和带有 gcc 5.2.0 的 rhel6.4 机器上是:
sizeof(int): 4
1
0
1
0
根据“Integer promotions”,2147483648u
的类型为 unsigned int
(即使没有 u
后缀),-2147483648
的类型为 int
(像往常一样)。为什么显式转换的结果不同?
根据“Usual arithmetic conversions”,本段适用:
Otherwise, the signedness is different: If the operand with the
unsigned type has conversion rank greater or equal than the rank of
the type of the signed operand, then the operand with the signed type
is implicitly converted to the unsigned type
这意味着正确的结果好像是:
2147483648u > 2147483648u
2147483648u != 2147483648u
被执行,因为在 32 位中,有符号 -2^31 和无符号 2^31 具有相同的表示形式。换句话说,铸造的结果是正确的。怎么回事?
我觉得不知何故,更高级别的整数提升是在没有强制转换的情况下应用的,所以我得到了例如双方都进行 64 位签名促销 - 但为什么呢?
两个可执行文件都编译为64位,这能发挥作用吗?
没有负整数常量。只有应用一元 -
运算符的正值。
因为 2147483648 > INT_MAX
,将 2147483648
提升为下一个更大的有符号整数类型(因为你没有附加 u
)整数类型,before -
已应用。
顺便说一下,这就是为什么 INT_MIN
在 <limits.h>
中通常被定义为 (-INT_MAX - 1)
的原因。 ;-)
#include <stdio.h>
int main() {
printf("sizeof(int): %zu\n", sizeof(int));
printf("%d\n", 2147483648u > -2147483648);
printf("%d\n", ((unsigned int)2147483648u) > ((int)-2147483648));
printf("%d\n", 2147483648u != -2147483648);
printf("%d\n", ((unsigned int)2147483648u) != ((int)-2147483648));
return 0;
}
此代码在 C 和 C++ 中的输出,在 cygwin64 和带有 gcc 5.2.0 的 rhel6.4 机器上是:
sizeof(int): 4
1
0
1
0
根据“Integer promotions”,2147483648u
的类型为 unsigned int
(即使没有 u
后缀),-2147483648
的类型为 int
(像往常一样)。为什么显式转换的结果不同?
根据“Usual arithmetic conversions”,本段适用:
Otherwise, the signedness is different: If the operand with the unsigned type has conversion rank greater or equal than the rank of the type of the signed operand, then the operand with the signed type is implicitly converted to the unsigned type
这意味着正确的结果好像是:
2147483648u > 2147483648u
2147483648u != 2147483648u
被执行,因为在 32 位中,有符号 -2^31 和无符号 2^31 具有相同的表示形式。换句话说,铸造的结果是正确的。怎么回事?
我觉得不知何故,更高级别的整数提升是在没有强制转换的情况下应用的,所以我得到了例如双方都进行 64 位签名促销 - 但为什么呢?
两个可执行文件都编译为64位,这能发挥作用吗?
没有负整数常量。只有应用一元 -
运算符的正值。
因为 2147483648 > INT_MAX
,将 2147483648
提升为下一个更大的有符号整数类型(因为你没有附加 u
)整数类型,before -
已应用。
顺便说一下,这就是为什么 INT_MIN
在 <limits.h>
中通常被定义为 (-INT_MAX - 1)
的原因。 ;-)