~~PAGEIMAGE:code:c:macro:media:20231026-224238.png~~ ====== C Macro Expansion Rules ====== {{template>:meta:template:pageinfo#tpl |desc=Introduce macro expansion rules in **C**.}} * ''#'' convert macro parameter to string. * ''##'' combine multiple tokens into one token. * Nested macro expansion rules * The preprocessor will first process macro parameters until they are expanded to non-macro parameters or blocked by ''# ''or ''##''. * The expansion of macro parameters will be blocked by ''#'' or ''##''. That is, the expansion of macro parameters will stop and then the pre-processor will use the expanded macro parameters to expand the macro. There are some examples to help understanding. ==== Example 1 ==== #define str(a) #a #define foo(a, b) a ## b str(x) > "x" foo(x, y) > xy {{code:c:screenshot_from_2023-02-22_22-49-32.png?direct&615x436}} ==== Example 2 ==== #define str(_a) #_a #define A a #define B b #define foo(_a, _b) _a##_b #define foo2(_a, _b) foo(_a, _b) foo2(A, B) > foo2(a, b) > ab foo(A, B) # Because A and B are arguments to foo, the extension of A and B are blocked by ##. > AB str(foo2(A, B)) # Because foo2 is an argument to foo, the extension of foo2 is blocked by #. > "foo2(A, B)" {{code:c:screenshot_from_2023-02-22_22-42-02.png?direct&624x468}} ==== Example 3 ==== #define A a #define B b #define foo(_a, _b) _a##_b _a foo(A, B) > AB A > AB a {{code:c:screenshot_from_2023-02-22_22-59-46.png?direct&634x251}}