我正在阅读源代码文件。但是我卡在了下面这行
while (isspace (* bp & 0xff))
++ bp;
我知道基本的想法是删除空格。但是我不知道 0xff
在下面的函数中到底在做什么。
static enum tokens scan (const char * buf)
{
static const char * bp;
if (buf)
bp = buf; /* new input line */
while (isspace (* bp & 0xff))
++ bp;
if (isdigit (* bp & 0xff) || * bp == '.')
{
errno = 0;
token = NUMBER, number = strtod (bp, (char **) & bp);
if (errno == ERANGE)
error ("bad value: %s", strerror (errno));
}
else
token = * bp ? * bp ++ : 0;
return token;
}
最佳答案
isspace
函数和另一个ctype.h
函数需要一个int
作为参数。来自 C11 标准第 7.4/1 节:
The header declares several functions useful for classifying and mapping characters. In all cases the argument is an
int
, the value of which shall be representable as anunsigned char
or shall equal the value of the macroEOF
. If the argument has any other value, the behavior is undefined.
这意味着如果您有如下代码:
char ch = 'é'; // same as: char ch = -126; for some code pages
isspace(ch);
然后这个调用导致undefined behaviour .
这样做的理由是该函数可以作为查找表来实现:#define isspace(x) space_table[x]
导致未定义的行为当然是不好的,所以 isspace(ch)
是错误的。修复代码的正确方法是:
isspace( (unsigned char)ch );
在使用 2 的补码算法的机器上,ch & 0xFF
完全等同于 (unsigned char)ch
。
在不使用 2 的补码的机器上,它会查找错误的值(但不会导致未定义的行为)。
也许您的程序员乐于假设他的代码永远不会在非 2 的补码机器上运行,并且他认为 & 0xFF
比强制转换更美观。
关于c - isspace (ch & 0xff) 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32667603/