#include <stdio.h>
#include <conio.h>
int main()
{
char a=-128;
while(a<=-1)
{
printf("%c\n",a);
a++;
}
getch();
return 0;
}
上面代码的输出与下面代码的输出相同
#include <stdio.h>
#include <conio.h>
int main()
{
unsigned char a=+128;
while(a<=+254)
{
printf("%c\n",a);
a++;
}
getch();
return 0;
}
那为什么要用unsigned char
和signed char
呢?
最佳答案
K & R,章节和诗句,p. 43 和 44:
There is one subtle point about the conversion of characters to integers. The language does not specify whether variables of type char are signed or unsigned quantities. When a char is converted to an int, can it ever produce a negative integer? The answer varies from machine to machine, reflecting differences in architecture. On some machines, a char whose leftmost bit is 1 will be converted to a negative integer ("sign extension"). On others, a char is promoted to an int by adding zeros at the left end, and thus is always positive. [...] Arbitrary bit patterns stored in character variables may appear to be negative on some machines, yet positive on others. For portability, specify signed or unsigned if non-character data is to be stored in char variables.
关于c - 由于从 -128 到 -1 的字符与从 +128 到 +255 的字符相同,那么使用 unsigned char 有什么意义呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36147357/