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

Why does the char variable get 'b' from assigning 'ab' instead of 'a'?

char c = 'ab';

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

Print

c: b
+5
source share
5 answers

This is an implementation defined as earlier answers already say.

My gcc treats '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';

It can be considered as:

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

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

+5
source

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

int. , , , . , (, 'ab') escape-, , .

+10

C11 (§6.4.4.4 " " al10 p69):

10 - [...] , (, 'ab') escape-, , . [...]

+5

'ab' int, char .

+1

: , , . , OP , , "b" "a" . , .

byte order. That is why you get "b" instead of "a". Because of how it is represented in your machine memory. And your car is probably not numerous.

Try this on sparc or on mipsbe or on your hand, and you can get "a" instead of "b".

In any case, I hope you are not dependent on this for the actual production code.

-1
source

All Articles