Simple demonstration
The following simple example of the token paste operator aims at demonstrating how it can be used.
First, a simple macro with two arguments is defined: PASTE_TWO_TOKENS
. When the macro is used (and expanded), it simply concatenates the two arguments.
If PASTE_TWO_TOKENS
is used with two tokens that have previoulsy been #defined
, the macro does not substitute the tokens with their defined value. In order to do that, another macro needs to be created: PASTE_TWO_TOKENS_INDIRECT
. In the example, this macro simply passes the tokens to PASTE_TWO_TOKENS
. However, while they're being forwared to PASTE_TWO_TOKENS
, they're also expaned.
PASTE_TWO_TOKENS_INDIRECT
is also needed, for example, to expand predefined macros such as
__COUNTER__
and concatenate it.
#define PASTE_TWO_TOKENS(token_1, token_2) token_1 ## token_2
PASTE_TWO_TOKENS(Hello, World) // HelloWorld
#define T1 Hello
#define T2 World
PASTE_TWO_TOKENS(T1, T2) // T1T2
#define PASTE_TWO_TOKENS_INDIRECT(token_1, token_2) PASTE_TWO_TOKENS(token_1 , token_2)
PASTE_TWO_TOKENS_INDIRECT( T1 , T2 ) // HelloWorld
PASTE_TWO_TOKENS_INDIRECT( T1 , UNDEF ) // Hello
PASTE_TWO_TOKENS(Cnt, __COUNTER__) // Cnt__COUNTER__
PASTE_TWO_TOKENS_INDIRECT(Cnt, __COUNTER__) // Cnt0
PASTE_TWO_TOKENS_INDIRECT(Cnt, __COUNTER__) // Cnt1