How to determine the result of assigning multi-character char constant to a char variable?

Why a char variable gets 'b' from assignment of 'ab', rather 'a'?

char c = 'ab';

printf("c: %c\n", c);

Prints:

c: b

According to the standard, it is implementation defined. From 6.4.4.4 Character constants:

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 (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined.


This is implementation defined as earlier answers already say.

My gcc handles 'ab' as an int. The following code:

printf( "sizeof('ab') = %zu \n", sizeof('ab') );
printf( "'ab' = 0x%08x \n", 'ab' );
printf( "'abc' = 0x%08x \n", 'abc' );

prints:

sizeof('ab') = 4
'ab' = 0x00006162
'abc' = 0x00616263

In your code, the line:

char c = 'ab';

Can be considered as:

char c = (char)(0x00006162 & 0xFF);

So c gets the value of the last char of 'ab'. In this case it is 'b' (0x62).


The value of an integer multi-character constant is implementation-defined, according to C11 standard (§6.4.4.4 "Character constants" al10 p69) :

10 - [...] 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. [...]


Because 'ab' has type int and a char can only hold one byte.