我对以下代码感到困惑:
#include <stdio.h> #include <stdint.h> int main(int argc,char ** argv) { uint16_t a = 413; uint16_t b = 64948; fprintf(stdout,"%u\n",(a - b)); fprintf(stdout,((uint16_t) (a - b))); return 0; }
返回:
$gcc -Wall test.c -o test $./test 4294902761 1001 $
似乎表达式(a-b)具有类型uint32_t.
我不明白为什么因为两个运算符都是uint16_t.
任何人都可以向我解释这个吗?
解决方法
C标准非常清楚地解释了这一点(§6.5.6加法运算符):
If both operands have arithmetic type,the usual arithmetic conversions are performed on them.
(§6.3.1.8通常的算术转换):
… the integer promotions are performed on both operands.
(§6.3.1.1布尔,字符和整数):
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参数被解释为它的二进制补码表示,并且打印出来.