printf too smart casting from char to int?

不想你离开。 提交于 2019-12-23 07:57:24

问题


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.


回答1:


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.




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/3959674/printf-too-smart-casting-from-char-to-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!