C++ macro: The ## operator

C++ macro: The ## operator

1. The ## operator

The ## (double number sign) operator concatenates two tokens in a macro invocation (text and/or arguments) given in a macro definition.

The last token of the argument for x is concatenated with the first token of the argument for y.
x 的自变量的最后一个标记与 y 的自变量的第一个标记合并。

#define XY(x,y) x##y

Use the ## operator according to the following rules:

  1. The ## operator cannot be the very first or very last item in the replacement list of a macro definition.
    ## 运算符不能是宏定义的替换列表中的第一个或最后一个项。

  2. The last token of the item in front of the ## operator is concatenated with first token of the item following the ## operator.
    ## 运算符前面的项的最后一个标记与 ## 运算符后面的项的第一个标记合并。

  3. Concatenation takes place before any macros in arguments are expanded.

    在展开自变量中的任何宏之前进行合并。

  4. If the result of a concatenation is a valid macro name, it is available for further replacement even if it appears in a context in which it would not normally be available.

    如果合并的结果是有效的宏名称,那么即使它出现在通常不可用的上下文中,也可以进行进一步替换。

  5. If more than one ## operator and/or # operator appears in the replacement list of a macro definition, the order of evaluation of the operators is not defined.

    #define ArgArg(x, y) x##y
    #define ArgText(x) x##TEXT
    #define TextArg(x) TEXT##x
    #define TextText TEXT##text
    #define CHENG 1
    #define YONGQIANG 2

    ArgArg(123, 456)
    ArgArg(yong, qiang)
    ArgText(name)
    TextArg(book)
    TextText
    ArgArg(YONG, QIANG)

Result of macro expansion:

123456
yongqiang
nameTEXT
TEXTbook
TEXTtext
2

https://godbolt.org/

References

[1] Yongqiang Cheng, https://yongqiang.blog.csdn.net/

[2] The ## operator, https://www.ibm.com/docs/en/i/7.5?topic=directives-macro-definition

[3] 3 Macros, https://gcc.gnu.org/onlinedocs/cpp/Macros.html

相关推荐
Yongqiang Cheng1 个月前
C++ macro: Variadic macros (可变参数宏)
c++ macro·variadic macros·可变参数宏