C++ macro

| 分类 C++  | 标签 C++_std 

In C and C++ macro, note that a single ‘#’ will create a string from the given argument, regardless of what that argument contains, while the double ‘##’ will create a new token by concatenating the arguments. For example

#include <stdio.h>
#define f(a,b) a##b
#define g(a)   #a
#define h(a) g(a)

int main()
{
    printf("%s\n",h(f(1,2))); //This output is "12"
    printf("%s\n",g(f(1,2))); //This output is "f(1, 2)"
    return 0;
}

Here I will show the reason about the macro results. Macro arguments are completely macro-expanded before they are substituted into a macro body, unless they are stringified(#) or pasted(##) with other tokens. After substitution, the entire macro body, including the substituted arguments, is scanned again for macros to be expanded. The result is that the arguments are scanned twice to expand macro calls in them. Since #define h(a) g(a) and there is no # within the body of the macro, then f(1, 2) is macro-expanded before it is substituted into the macro body. Then we get g(12) and it is scanned again for macro to be expanded. We finally get the result “12”. However, for g(a) there is a # inside the macro body. So we just simply get “f(1, 2)” without the macro-expand for the argument of macro.

# and ## in macro (stackoverflow reference)

gnu macro


上一篇     下一篇