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.
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 char
s, something like:
char a = 'a';
printf("%d", a);
...what printf
receives would be of type int
, not type char
anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With