Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf too smart casting from char to int?

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.

like image 311
Hila's Master Avatar asked Oct 18 '10 13:10

Hila's Master


1 Answers

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.

like image 141
Jerry Coffin Avatar answered Oct 30 '22 21:10

Jerry Coffin