I suddenly noticed that i've used conversion specifier %d with type char although %d takes only type int.
How is it possible?
According to c standard, conversion specifier %d is corresponding to type int argument. And if any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
#include <stdio.h>
int main(void){
char a= 'A'; // 'A' = 65 in ASCII
printf("%c\n", a);
printf("%d\n", a);
return 0;
}
----- output -----
A
65
But whenever i compile the code like above , i always get output as intended.
Shouldn't i expect this output always?
Or, IS type char expanded to type int when passed to function's argument? So it can be 65 and i can use specifier %d with type char?
C 2018 6.5.2.2 7 says:
printfis declaredint printf(const char * restrict format, ...);, so, inprintf("%d\n", a);, the"%d"argument corresponds to theformatparameter, and theacorresponds to the..., making it part of the trailing arguments. So the default argument promotions are performed on it. These are specified in 6.5.2.2 6:The integer promotions are specified in 6.3.1.1 2:
Thus your
charargumentais automatically converted to anint, so it is the correct type for%d.