当我在阅读K&R时,我对这段代码感到困惑:
据说在这段代码中使用unsigned char是为了避免符号扩展带来的错误。这是我能想到唯一的情况,并给出下面的示例代码:
#include "syscalls.h"
int getchar(void)
{
char c;
return (read(0, &c, 1) == 1) ? (unsigned char)c : EOF;
}
据说在这段代码中使用unsigned char是为了避免符号扩展带来的错误。这是我能想到唯一的情况,并给出下面的示例代码:
char c = 0xf0; //11110000, just make highest bit > 1
printf("%i\n",(int)(unsigned char)c);
printf("%i\n",(int)c);
Output: 240 // 0...011110000
-16 // 1...111110000
实际上,ASCII 只有 0~127,最高位不能被赋值为 1。那么为什么在 K&R 中将 char 强制转换为 unsigned char?
char
需要限制在ASCII字符集中? - Paul R