将宏定义为逗号(用该宏分隔参数)在函数参数中正常工作,但在其他宏中无效

Defining a macro as comma (to separate arguemnts with that marco) works properly in functions arguments but not in other macros

我想出了一个问题的小例子

假设我有这个宏

#define and ,

我像 sum(a and b) 一样使用它,应该扩展为 sum(a, b)

我的问题是,如果 sum 是由宏定义的,用法示例会遇到 too few arguments ... 错误。

另一个我认为可能相关的问题,我猜会用同样的技巧解决,就是当我定义一个空宏并将它放在函数名和参数列表之间时。例如

#define of

现在,当我使用 sum of(1, 2) 时,编译器将 sum 视为函数,如果它是宏,则链接器会抛出 undefined reference 错误。

#define of
#define sum(a, b) a + b

int main()
{
    sum of(a, b); // undefined reference to `sum'
}

and 宏的问题是 a and b 在用 , 替换 and 之前被识别为宏参数。

6.10.3.1 Argument substitution

  1. After the arguments for the invocation of a function-like macro have been identified, argument substitution takes place. A parameter in the replacement list, unless preceded by a # or ## prepro- cessing token or followed by a ## preprocessing token (see below), is replaced by the corresponding argument after all macros contained therein have been expanded. Before being substituted, each argument’s preprocessing tokens are completely macro replaced as if they formed the rest of the preprocessing file; no other preprocessing tokens are available.

你的第二个问题类似但不相关。 of展开后,再展开sum已经来不及了,因为它不再被预处理器扫描:

6.10.3.4 Rescanning and further replacement

  1. After all parameters in the replacement list have been substituted and # and ## processing has taken place, all placemarker preprocessing tokens are removed. The resulting preprocessing token sequence is then rescanned, along with all subsequent preprocessing tokens of the source file, for more macro names to replace.