C 中的整数提升示例
Integer promotion example in C
void foo(void) {
unsigned int a = 6;
int b = -20;
if (a+b > a) {
printf("> a");
} else {
printf("< a");
}
}
我想了解上面的整数提升示例是怎么回事。我知道 a = 6
和 b = -20
的输出应该是 > a
,因为 b
被提升为 unsigned int
。但是,如果我分配 b = -5
,输出将变为 < a
。由于值 b = -5
也被提升为 unsigned int
,因此在这种情况下输出不应该相同吗?
这与将有符号值转换为无符号值的方法有关。
C standard 的第 6.3.1.3 节关于有符号和无符号整数的转换规定了这是如何发生的:
2 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.60)
...
60) The rules describe arithmetic on the mathematical value, not the value of a given type of expression.
在您的示例中 b
等于 -20,当它转换为无符号时 UINT_MAX + 1
被添加到该值,因此转换后的值为 UINT_MAX - 19
。然后,当您添加 a
(6) 的值时,您会得到 UINT_MAX - 13
。此值大于 a
,因此打印 "> a"
。
如果您将 b
设置为 -5,则转换后的值为 UINT_MAX - 4
。将 6 添加到此得到 UINT_MAX + 2
。由于 unsigned int
值的数学运算以 UINT_MAX + 1
为模,实际结果为 1。这小于 6,因此打印 "< a"
。
此外,这里发生的不是整数提升,而是整数转换。如果表达式中的任何整数类型的秩小于 int
,则首先发生提升。这里不是这种情况。
void foo(void) {
unsigned int a = 6;
int b = -20;
if (a+b > a) {
printf("> a");
} else {
printf("< a");
}
}
我想了解上面的整数提升示例是怎么回事。我知道 a = 6
和 b = -20
的输出应该是 > a
,因为 b
被提升为 unsigned int
。但是,如果我分配 b = -5
,输出将变为 < a
。由于值 b = -5
也被提升为 unsigned int
,因此在这种情况下输出不应该相同吗?
这与将有符号值转换为无符号值的方法有关。
C standard 的第 6.3.1.3 节关于有符号和无符号整数的转换规定了这是如何发生的:
2 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.60)
...
60) The rules describe arithmetic on the mathematical value, not the value of a given type of expression.
在您的示例中 b
等于 -20,当它转换为无符号时 UINT_MAX + 1
被添加到该值,因此转换后的值为 UINT_MAX - 19
。然后,当您添加 a
(6) 的值时,您会得到 UINT_MAX - 13
。此值大于 a
,因此打印 "> a"
。
如果您将 b
设置为 -5,则转换后的值为 UINT_MAX - 4
。将 6 添加到此得到 UINT_MAX + 2
。由于 unsigned int
值的数学运算以 UINT_MAX + 1
为模,实际结果为 1。这小于 6,因此打印 "< a"
。
此外,这里发生的不是整数提升,而是整数转换。如果表达式中的任何整数类型的秩小于 int
,则首先发生提升。这里不是这种情况。