C

C Macro Expansion Rules

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.

#define str(a) #a #define foo(a, b) a ## b

str(x)
   > "x"

foo(x, y)
   > xy

#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)"


#define A a
#define B b
#define foo(_a, _b) _a##_b _a

foo(A, B)
   > AB A
       > AB a


F P W​ D Z