printf 从 char 到 int 的转换太智能了吗?

发布于 2024-09-27 14:33:48 字数 220 浏览 2 评论 0原文

为什么以下调用:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

舂唻埖巳落 2024-10-04 14:33:48

在这种情况下,printf 接收到的参数将是 int 类型。

首先,传递给 printf 的任何内容(第一个参数除外)都会经历“默认提升”,这意味着(除其他外)charshort 都提升为int 在被传递之前。因此,即使您传递的内容确实具有 char 类型,当它到达 printf 时,它也会具有 int 类型。在您的情况下,您使用的是字符文字,无论如何它已经具有类型 int

scanf 和其他采用可变参数的函数也是如此。

其次,即使没有默认的提升,C 中的字符文字也已经具有 int 类型(第 6.4.4.4/10 节):

整型字符常量的类型为 int。

因此,在这种情况下,值以 int 类型开头,并且不会提升 - 但即使您以 char 开头,类似:

char a = 'a';

printf("%d", a);

...what < code>printf 接收到的类型将是 int 类型,而不是 char 类型。

In this case, the parameters received by printf will be of type 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.

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):

An integer character constant has type int.

So, in this case the values start with type int, and aren't promoted--but even if you started with chars, something like:

char a = 'a';

printf("%d", a);

...what printf receives would be of type int, not type char anyway.

萌酱 2024-10-04 14:33:48

C 中,char 文字是int 类型的值。

In C, a char literal is a value of type int.

清风挽心 2024-10-04 14:33:48

它会打印您输入的字符的 DEC ASCII。

it prints the DEC ASCII for the characters entered by you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文