C Language | Preprocessing | Token Pasting ##
This article explains the ## operator, which combines arbitrary tokens. It is mainly used to join a parameter passed to a macro with another macro or value.
Token-Pasting Operator
In addition to the stringification operator, macros defined with #define support another important preprocessing operator: ##, the token-pasting operator. It can be used in ordinary and function-like macros.
## Operator
token1 ## token2
The token-pasting operator joins the token on its left with the token on its right. This happens at the source level during preprocessing, not dynamically while the program runs. For example, WIN ## 32 becomes WIN32, and WIN ## 16 becomes WIN16.
#define INT16 short
#define INT32 int
#define INT(n) INT ## n
The INT() macro joins the token INT with the parameter n. For example, INT(16) expands to INT16, which then expands to short.
Code
#include <stdio.h>
#define TOKEN0 "Kitty"
#define TOKEN1 "Kitten"
#define TOKEN(n) TOKEN ## n
int main() {
printf("%s\n" , TOKEN(0));
printf("%s\n" , TOKEN(1));
return 0;
}
The TOKEN() macro receives a token suffix. For example, TOKEN(0) joins TOKEN and 0, producing TOKEN0. Because TOKEN0 is defined with #define, it expands to "Kitty".
A new token created with ## must be valid. An invalid token causes a compile error. Remember that token pasting is source-level expansion performed before compilation.