printf 从 char 到 int 的转换太智能了吗?
为什么以下调用:
printf("%d %d", 'a', 'b');
会产生“正确”的 97 98
值? %d 表示函数必须读取 4 个字节的数据,而 printf 不应该能够告诉接收到的参数的类型(除了格式字符串),那么为什么打印的数字不是 |a|| b||垃圾||垃圾|
?
提前致谢。
Why does the following call:
printf("%d %d", 'a', 'b');
result in the "correct" 97 98
values?
%d indicates the function has to read 4 bytes of data, and printf shouldn't be able to tell the type of the received arguments (besides the format string), so why isn't the printed number |a||b||junk||junk|
?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这种情况下,
printf
接收到的参数将是int
类型。首先,传递给 printf 的任何内容(第一个参数除外)都会经历“默认提升”,这意味着(除其他外)
char
和short
都提升为int
在被传递之前。因此,即使您传递的内容确实具有 char 类型,当它到达printf
时,它也会具有int
类型。在您的情况下,您使用的是字符文字,无论如何它已经具有类型int
。scanf 和其他采用可变参数的函数也是如此。
其次,即使没有默认的提升,C 中的字符文字也已经具有
int
类型(第 6.4.4.4/10 节):因此,在这种情况下,值以
int
类型开头,并且不会提升 - 但即使您以char
开头,类似:...what < code>printf 接收到的类型将是
int
类型,而不是char
类型。In this case, the parameters received by
printf
will be of typeint
.First of all, anything you pass to printf (except the first parameter) undergoes "default promotions", which means (among other things) that
char
andshort
are both promoted toint
before being passed. So, even if what you were passing really did have type char, by the time it got toprintf
it would have typeint
. In your case, you're using a character literal, which already has typeint
anyway.The same is true with scanf, and other functions that take variadic parameters.
Second, even without default promotions, character literals in C already have type
int
anyway (§6.4.4.4/10):So, in this case the values start with type
int
, and aren't promoted--but even if you started withchar
s, something like:...what
printf
receives would be of typeint
, not typechar
anyway.在
C
中,char 文字是int
类型的值。In
C
, a char literal is a value of typeint
.它会打印您输入的字符的 DEC ASCII。
it prints the DEC ASCII for the characters entered by you.