Difference between in signed and unsigned char in c
What is the difference between signed and unsigned char
in C ? When I tried to run the following code without unsigned
it entered an infinite loop as the range of signed char is up to 127
(Why is it signed by default ?). But when I added unsigned
(whose range is up to 255) it works fine. What's the reason ?
#include <stdio.h>
int main() {
unsigned char x;
x = 0;
while (x <= 225) {
printf("%c=%dn", x, x);
x = x + 1;
}
return 0;
}
There's no dedicated "character type" in C language. char is an integer type, same (in that regard) as int, short and other integer types.
If you are using numbers as char
From 3.9.1 Fundamental types
Plain char, signed char, and unsigned char are three distinct types. A char, a signed char, and an unsigned char occupy the same amount of storage and have the same alignment requirements (3.11); that is, they have the same object representation.
With the statement
x=x+1;
there are a few things happening.
First the expression x + 1
will be evaluated. That will lead to usual arithmetic conversion of the value in x
so it becomes promoted to an int
. The (promoted) value will be increased by 1
, and then the result will be assigned back to x
. And here the problems start.
Because the result of x + 1
is an int
it needs to be converted back to a ( signed
) char
. This is done through integer conversion and when converting from a larger signed type (like int
) to a smaller signed type (like signed char
) when the value can't fit in the smaller type (like trying to store 128
in a signed char
) the behavior is implementation defined.
What happens in practice is that the value becomes negative (the value is increased from 0x7f
to 0x80
which is -128
in two's complement (the most common encoding for negative numbers)). This further leads to x
being less than 225
forever and your infinite loop.
Signed char range is -128 to 127 . Unsigned char range is 0 to 255. Your while loop will work as expected if the x variable defined as unsigned char.
If you define the variable with signed char, then the variable 'x' laid between -128 to 127. It is always less than 255.
链接地址: http://www.djcxy.com/p/96710.html