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
printfwill be of typeint.First of all, anything you pass to printf (except the first parameter) undergoes “default promotions”, which means (among other things) that
charandshortare both promoted tointbefore being passed. So, even if what you were passing really did have type char, by the time it got toprintfit would have typeint. In your case, you’re using a character literal, which already has typeintanyway.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
intanyway (§6.4.4.4/10):So, in this case the values start with type
int, and aren’t promoted–but even if you started withchars, something like:…what
printfreceives would be of typeint, not typecharanyway.