C语言中的类型提升 [英] type promotion in C

查看:129
本文介绍了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\n", (a - b));
    fprintf(stdout, "%u\n", ((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节加法运算符"):

The C standard explains this quite clearly (§6.5.6 Additive Operators):

如果两个操作数都具有算术类型,则对它们执行通常的算术转换.

(第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;否则,该值将转换为int. ...这些称为整数促销.整数促销未更改所有其他类型.

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的值,因此在执行减法之前,ab会转换为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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆