Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C programming Char possible values

Tags:

c

char

I am trying to learn C and now I am learning chars. I have read some where that char can be signed and unsigned. This part I get but when I use an unsigned char(which I thought could held value 0-255)

printf("%c", 400); 

or even

printf("%c\n", (unsigned char)400);

it prints out an É

Why is this?

like image 268
Haagenti Avatar asked Dec 30 '12 13:12

Haagenti


2 Answers

According to the C99 Standard, when c format specifier is provided to printf with no l length modifier,

the int argument is converted to an unsigned char, and the resulting character is written.

This means that 400 is converted to an unsigned char, which is 400 % 256, or 144. Then, the character that corresponds to 144 is written out. This is a UNICODE control sequence, so that É character that you see is system-dependent.

like image 137
Sergey Kalinichenko Avatar answered Sep 22 '22 05:09

Sergey Kalinichenko


unsigned char c = 400;
printf("%d",c);

Guess what, you will get 144 printed. That's because an overflow occurred in c.

An unsigned char takes exactly 8 bits of memory (on almost every platform), so that it's a variable in the range of 00000000(0) ~ 11111111(255). Whenever you try to assign a number which is more than 8 bits in binary to an unsigned char, the left superfluous bits will overflow and lost.

In your case, you tried to assign 400 to an unsigned char:

400 = 110010000 which has 9 bits, so the highest 1 will lost, then you got 10010000 actually assigned to the char, which is 144 in decimal.

When you print it as %d, you will get 144; When you print it as %c, you will get É which is the 144th character in the Extended ASCII Codes (in your case).

like image 42
Skyler Avatar answered Sep 18 '22 05:09

Skyler