从printf的字符太聪明铸造为int? [英] printf too smart casting from char to int?
问题描述
为什么下面的调用:
printf("%d %d", 'a', 'b');
结果正确的 97 98
值?
%d表示函数读取4个字节的数据,和printf不应该能够告诉的接收参数的类型(除了格式字符串),那么为什么不印号码 |一个|| b ||垃圾||垃圾|
先谢谢了。
推荐答案
在这种情况下,的printf
接收到的参数将类型 INT
。
In this case, the parameters received by printf
will be of type int
.
首先,任何你传递给printf(除了第一个参数)经历了默认促销,这意味着(除其他事项外)的字符
和短
都在传递前晋升为 INT
。所以,即使你传递什么确实有类型char,通过它得到的printf
那就键入 INT $ C $时间C>。在你的情况,你使用一个字符,并已经有键入
INT
反正。
First of all, anything you pass to printf (except the first parameter) undergoes "default promotions", which means (among other things) that char
and short
are both promoted to int
before being passed. So, even if what you were passing really did have type char, by the time it got to printf
it would have type int
. In your case, you're using a character literal, which already has type int
anyway.
同样是scanf函数,以及采取可变参数的参数等功能如此。
The same is true with scanf, and other functions that take variadic parameters.
其次,即使没有默认促销活动,在C字符文字已经有键入 INT
反正(§6.4.4.4/ 10):
Second, even without default promotions, character literals in C already have type int
anyway (§6.4.4.4/10):
这是整型字符常量的类型为int。
An integer character constant has type int.
因此,在这种情况下,值开始键入 INT
,并且不松口 - 但即使你开始与字符
S,是这样的:
So, in this case the values start with type int
, and aren't promoted--but even if you started with char
s, something like:
char a = 'a';
printf("%d", a);
...什么的printf
接收将类型 INT
,不要键入字符
反正。
...what printf
receives would be of type int
, not type char
anyway.
这篇关于从printf的字符太聪明铸造为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!