views:

76

answers:

4

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.

+4  A: 

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.

Jerry Coffin
Default promotions? Really? Since when do varargs do default promotions? Isn't it just that the type of a character literal is `int`?
Oli Charlesworth
Yes and no -- yes, a char literal has type `int`, but even if he assigned it to a `char` and passed that, `printf` would still receive an `int`, so it's pretty much irrelevant.
Jerry Coffin
Right up, Jerry. Thanks.
Hila's Master
+2  A: 

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

pmg
A: 

A single char is synonymous with an integer, they can be used interchangeably in C.

Rudu
A: 

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

Sunscreen