7

Fedora Linux 上最新版本的 gcc 和 clang 编译以下程序没有错误:

#include <ctype.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
    char c = 'a';
    if islower(c)
        printf("%d", c);
    else
        printf("%c", c);
    return 0;
}

这是 gcc 4.7.2 和 clang 3.0。相比之下,在我的 Mac 上,gcc 4.2.1 和 Apple clang 4.1 都抱怨“if islower(c)”行中缺少括号,正如预期的那样。在所有情况下,我都使用“-std=c99”运行编译器。

这是最新版本的 gcc 和 clang 中的错误,C 语言中的怪癖,还是其他什么?C99 标准(http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1256.pdf第 133 页)似乎在所有情况下都要求在 if 表达式周围加上括号。

4

2 回答 2

13

这很可能islower()是一个宏,并且扩展添加了括号。

发布来自 GCC 的预处理输出,您可以通过使用-E选项进行编译来获得。

于 2012-10-02T15:08:12.280 回答
10

我只是查看了ctype.h位于的文件/usr/include/ctype.h并找到了以下定义islower

#define islower(c)  __isctype((c), _ISlower)

转到__isctype()我发现的定义:

#define __isctype(c, type) \
  ((*__ctype_b_loc())[(int) (c)] & (unsigned short int) type)

因此,您的代码if islower(c)扩展为:

if ((*__ctype_b_loc())[(int) (c)] & (unsigned short int) _ISlower)

正如 unwind 所说,在扩展过程中添加了括号。

于 2012-10-02T15:28:02.290 回答