Why are there 2 levels of indirection in the definition of macro ##

The macro definitions below have 2 levels of indirection before the actual insert operation:

#define MACRO_JOIN(a, b)  MACRO_JOIN1(a, b)
#define MACRO_JOIN1(a, b) MACRO_JOIN2(a, b)
#define MACRO_JOIN2(a, b) a##b

I know what we need MACRO_JOIN1because it has no insert or line so that its arguments can be expanded first.

But what is the purpose of the second indirection MACRO_JOIN? In what situations MACRO_JOINwill it work, but will not MACRO_JOIN1?

+4
source share
1 answer

Forcing additional expansion can make a difference when the initial expansion leads to something that can be expanded further. Trivial example:

#define MACRO(x) x
#define EXPAND(x) x
#define NOEXPAND()

is an:

MACRO NOEXPAND() (123)

MACRO (123). , , :

EXPAND(MACRO NOEXPAND() (123))

:

123

, , , : , , - , . .

, MACRO_JOIN:

MACRO_JOIN(123, MACRO NOEXPAND() (456)) // expands to 123456
MACRO_JOIN1(123, MACRO NOEXPAND() (456)) // expands to 123MACRO (456)
+6

Source: https://habr.com/ru/post/1648886/


All Articles