c - 为什么预处理器宏会忽略括号中的语句

标签 c c-preprocessor

跟随我的 ( duplicate ) question (并按照 StoryTeller 的建议)

为什么预处理器宏会忽略括号中的函数名称?

#include  <stdio.h>
#include <stdlib.h>
#define abs(x) ((x))

int main(void)
{
    printf("%d\n", abs(-1)); // output: -1
    printf("%d\n", (abs)(-1)); // output: 1
    return 0;
}

这是在标准中定义的吗?

最佳答案

预处理器的宏替换指定如下:

6.10.3 Macro replacement / p10 - 强调我的:

A preprocessing directive of the form

# define identifier lparen identifier-list<opt> ) replacement-list new-line
# define identifier lparen ... ) replacement-list new-line
# define identifier lparen identifier-list , ... ) replacement-list new-line

defines a function-like macro with parameters, whose use is similar syntactically to a function call. The parameters are specified by the optional list of identifiers, whose scope extends from their declaration in the identifier list until the new-line character that terminates the #define preprocessing directive. Each subsequent instance of the function-like macro name followed by a ( as the next preprocessing token introduces the sequence of preprocessing tokens that is replaced by the replacement list in the definition (an invocation of the macro). The replaced sequence of preprocessing tokens is terminated by the matching ) preprocessing token, skipping intervening matched pairs of left and right parenthesis preprocessing tokens. Within the sequence of preprocessing tokens making up an invocation of a function-like macro, new-line is considered a normal white-space character.

它以粗体显示在此处。要进行替换,宏名称后的下一个预处理标记必须是(。当它是)时,例如当宏在括号中,不能发生替换。

因此,我们只剩下括号中的函数名称,这是一个与函数指示符相同的表达式。

关于c - 为什么预处理器宏会忽略括号中的语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49730404/

相关文章:

c - 将文件描述符传递给线程并在函数中使用它(作业)

c - getopt 中的 opterr 声明

c - 计算结果为零并可用作语句的函数宏

c++ - 使用可变参数重载宏

c++ - pp-tokens 还剩下哪些字符?

c++ - 使用预处理器宏取消定义函数

c - Fortran-C 互操作性和 float 组

c - 使用 execvp 在 Ubuntu 上用 C 语言构建 shell

c - 调用 fcntl() 的目的是什么,文件描述符为 -1,cmd 为 F_GETFL?

c++ - 模板参数计算