Printing a char with printf

user535450 picture user535450 · Jan 19, 2011 · Viewed 167k times · Source

Are both these codes the same

char ch = 'a';
printf("%d", ch);

Will it print a garbage value?

I am confused about this

printf("%d", '\0'); 

Will this print 0 or garbage value? Because when i do this

printf("%d", sizeof('\n')); 

It prints 4. Why is sizeof('\n') 4 bytes? The same thing in C++ prints 1 bytes. Why is that?

So here's the main question

in c language is printf("%d", '\0') supposed to print 0

and in C++ printf("%d", '\0') supposed to print garbage?

Answer

peoro picture peoro · Jan 19, 2011

%d prints an integer: it will print the ascii representation of your character. What you need is %c:

printf("%c", ch);

printf("%d", '\0'); prints the ascii representation of '\0', which is 0 (by escaping 0 you tell the compiler to use the ascii value 0.

printf("%d", sizeof('\n')); prints 4 because a character literal is an int, in C, and not a char.