char ch = 'AB';
printf("ch is %d\n",ch); // Output "ch is 66"
Why it is printing the decimal value of second character,why not the first character's decimal value?
'AB'
is an int
character constant.
The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined. C11 §6.4.4.4 10
Example: Your output may differ.
printf("ch is %d\n",'AB'); // prints "ch is 16706"
16706 is the same value as 0x4142 which is the concatenated value of ASCII A
and B
. A printout out of ch is 16961
(0x4241) or ch is 1111556096
(0x42410000) or others is possible. It is implementation defined behavior.
Assigning 16706
to an char
is either implementation defined behavior or well defined - depending on if char
is signed or unsigned. A common ID result is to assign the lower byte, or 0x42
.
`
printf("ch is %d\n", ch); // prints "ch is 66"
Assigning a value outside the char
range to a char
may raise a warning.
// Example warning
// warning: overflow in implicit constant conversion [-Woverflow]
char ch1 = 'AB';
char ch2 = 16706;
In addition, given the implementation defined nature of such consonant, the below may also warn:
// Example warning
// warning: multi-character character constant [-Wmultichar]
char ch1 = 'AB';
Use of multi-character character constant is limited to few select cases. So few that it is more likely a coding error that a good use.