简体   繁体   中英

C Programming: Using format specifiers

In the C language, The answer of

char c='61'; 
printf ("%d", c);

is 49. The answer of

char c='61'; 
printf ("%c", c); 

is 1. The answer of

char c=61; 
printf ("%d", c);

is 61. The answer of

char c=61; 
printf ("%c", c);

is = . How is this happening exactly?

In the first two cases,

 char c='61';

have implementation-defined behaviour and not standard complaint. Quoting C11 , chapter 6.4.5/P10

An integer character constant has type int. The value of an integer character constant containing a single character that maps to a single-byte execution character is the numerical value of the representation of the mapped character interpreted as an integer. The value of an integer character constant containing more than one character (eg, 'ab' ), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined. [....]

It may not be a valid behaviour on your environment. Your compiler might have issued a warning there. Something like

warning: multi-character character constant [-Wmultichar]
     char c='61';
            ^~~~
warning: overflow in implicit constant conversion [-Woverflow]

In other two cases, read about most common character encoding, ASCII .

  • When you print the integer value using %d , it prints the value 61 .

  • When you print the character representation of integer value 61 using %c , decimal value of 61 is for the ASCII character = . That gets printed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM