Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is %c used in C?

Tags:

c

According to K&R C section 1.6, a char is a type of integer. So why do we need %c. And why can't we use %d for everything?

like image 704
Shash Avatar asked Jun 08 '12 11:06

Shash


2 Answers

Because %d will print the numeric character code of the char:

printf("%d", 'a');

prints 97 (on an ASCII system), while

printf("%c", 'a');

prints a.

like image 159
Fred Foo Avatar answered Sep 20 '22 06:09

Fred Foo


While it's an integer, the %c interprets its numeric value as a character value for display. For instance for the character a:

If you used %d you'd get an integer, e.g., 97, the internal representation of the character a

vs

using %c to display the character 'a' itself (if using ASCII)

I.e., it's a matter of internal representation vs interpretation for external purposes (such as with printf)

like image 22
Levon Avatar answered Sep 23 '22 06:09

Levon