Why a char variable gets \'b\' from assignment of \'ab\', rather \'a\'?
char c = \'ab\';
printf(\"c: %c\\n\", c);
Prints:
Later edit: my answer was complementary to the ones before that stated pretty clearly that this is implementation specific behavior. I was under the impression the OP wanted to know, with that in mind, why the compiler chose 'b' over 'a'. Sorry if my answer was confusing.
Endianess. That's why you get 'b' instead of 'a'. Because of how that is represented in your machine's memory. And your machine is probably little endian.
Try it on a sparc or on a mipsbe or on an arm and you might get 'a' instead of 'b'.
In any case I hope you're not depending on this for actual production code.
Because 'ab' has type int and a char can only hold one byte.
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.
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. [...]
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).