C中的类型推广

我对以下代码感到困惑:
#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 an int; … 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参数被解释为它的二进制补码表示,并且打印出来.

相关文章

首先GDB是类unix系统下一个优秀的调试工具, 当然作为debug代...
1. C语言定义1个数组的时候, 必须同时指定它的长度.例如:int...
C++的auto关键字在C+⬑新标准出来之前基本...
const关键字是用于定义一个不该被改变的对象,它的作用是告诉...
文章浏览阅读315次。之前用C语言编过链表,这几天突然想用C+...
文章浏览阅读219次。碰到问题就要记录下来,防止遗忘吧。文章...