C 中有符号和无符号 char
有什么区别?当我尝试在没有 unsigned
的情况下运行以下代码时,它进入了一个无限循环,因为 signed char 的范围最大为 127
(为什么默认情况下它是签名的?)。但是当我添加 unsigned
(其范围最大为 255)时,它工作正常。这是什么原因?
#include <stdio.h>
int main() {
unsigned char x;
x = 0;
while (x <= 225) {
printf("%c=%d\n", x, x);
x = x + 1;
}
return 0;
}
最佳答案
C 语言中没有专门的“字符类型”。 char 是整数类型,(在这方面)与 int、short 和其他整数类型相同。
- 都是整数类型。
- 它们的大小相同(一个 btye)。
如果您使用数字作为字符
- 有符号字符,它至少提供 -127 到 127 范围。 (-128 至 127 很常见)
- Unsigned char,它至少提供 0 到 255 的范围。
来自3.9.1基本类型
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.
关于c - c中有符号和无符号字符之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45230345/