在没有括号的if语句中调用函数

时间:2012-10-02 15:05:51

标签: c syntax

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页)似乎都要求括号括起来。

2 个答案:

答案 0 :(得分:13)

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

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

答案 1 :(得分: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)

正如放松所说,在扩张过程中添加了括号。