gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:28:06 26 4
gpt4 key购买 nike

跟随我的 ( 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com