C 中的类型提升 [英] type promotion in C
问题描述
我对以下代码感到很困惑:
I am quite confused by the following code:
#include <stdio.h>
#include <stdint.h>
int main(int argc, char ** argv)
{
uint16_t a = 413;
uint16_t b = 64948;
fprintf(stdout, "%u
", (a - b));
fprintf(stdout, "%u
", ((uint16_t) (a - b)));
return 0;
}
返回:
$ gcc -Wall test.c -o test
$ ./test
4294902761
1001
$
似乎表达式 (a - b) 的类型是 uint32_t.我不明白为什么,因为两个运算符都是 uint16_t.
It seems that expression (a - b) has type uint32_t. I don't uderstand why since both operators are uint16_t.
谁能给我解释一下?
推荐答案
C 标准非常清楚地解释了这一点(§6.5.6 Additive Operators):
The C standard explains this quite clearly (§6.5.6 Additive Operators):
如果两个操作数都具有算术类型,则对它们执行通常的算术转换.
If both operands have arithmetic type, the usual arithmetic conversions are performed on them.
(第 6.3.1.8 节常用算术转换):
(§6.3.1.8 Usual Arithmetic Conversions):
...整数提升对两个操作数执行.
... the integer promotions are performed on both operands.
(第 6.3.1.1 节布尔值、字符和整数):
(§6.3.1.1 Boolean, characters, and integers):
如果一个int
可以表示原始类型的所有值,则将该值转换为int
;...这些被称为整数提升.所有其他类型都不会因整数提升而改变.
If an
int
can represent all values of the original type, the value is converted to anint
; ... These are called the integer promotions. All other types are unchanged by the integer promotions.
由于int
可以表示你平台上uint16_t
的所有值,a
和b
被转换为int
在执行减法之前.结果的类型为 int
,并作为 int
传递给 printf
.您已使用 int
参数指定了 %u
格式化程序;严格来说,这会调用未定义的行为,但在您的平台上,int
参数被解释为它的二进制补码表示,并被打印出来.
Since int
can represent all values of uint16_t
on your platform, a
and b
are converted to int
before the subtraction is performed. The result has type int
, and is passed to printf
as an int
. You have specified the %u
formatter with an int
argument; strictly speaking this invokes undefined behavior, but on your platform the int
argument is interpreted as it's twos-complement representation, and that is printed.
这篇关于C 中的类型提升的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!