c - isspace (ch & 0xff) 是什么意思?

标签 c

我正在阅读源代码文件。但是我卡在了下面这行

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 an unsigned char or shall equal the value of the macro EOF. 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/

相关文章:

c++ - 获取错误信息

c - 多维数组,不同方式表示grid[22][0]的地址

ios - 使用 openssl 在 C 中使用 PEM 证书以 DER 格式验证 PKCS7

c - 我使用 'exit(EXIT_FAILURE);' ,但随后出现错误

c - 如何计算文件中某个字符的出现次数?

c - 拦截来自进程的信号

c - 如何在编译时打印结构成员的偏移量?

c++ - 明显的 CUDA 魔法

C编程: How to get directory name?

c - 用 C 语言编写归并排序伪代码过程