微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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参数被解释为它的二进制补码表示,并且打印出来.

原文地址:https://www.jb51.cc/c/117401.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐