Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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

char c = 'ab';

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

Prints:

c: b
like image 512
Victor S Avatar asked Jul 31 '12 09:07

Victor S


2 Answers

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.

like image 82
hmjd Avatar answered Sep 21 '22 20:09

hmjd


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).

like image 38
SKi Avatar answered Sep 21 '22 20:09

SKi