C Reference ยท Preprocessor
The ## (token pasting) operator
Reference for the C ## operator: join two tokens into one inside a macro, generate function and variable names, and avoid the expansion-order traps.
The ## operator glues two tokens into a single token during macro expansion. a ## b with a = value_ and b = 1 becomes the identifier value_1. It lets a macro generate names: a family of functions, a struct per type, a counter-based unique variable.
Operands of ## are not macro-expanded before pasting, only after. When you need the value of a macro as part of the new name, add one level of indirection, as with the # operator.
#define CONCAT(a, b) a##b CONCAT(user, _id) /* user_id */
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
#define MACRO(a, b) a ## b #define MACRO(a) prefix_ ## a
| Name | Description |
|---|---|
a ## b |
Joins the last token of a and the first token of b into one token. |
Errors / undefined behavior: the result must be a valid single preprocessing token. Pasting + and - into +- is undefined behavior (it is not one token); compilers report an error. ## cannot be the first or last token of a replacement list.
Usage notes
- Operands are not expanded first.
CONCAT_DIRECT(PREFIX, one)becomesPREFIXone. To paste the expansion, route through a second macro (CONCAT). The second TryIt shows both results. __LINE__and__COUNTER__give unique suffixes, but only through the two-step form.__COUNTER__is a GCC, Clang and MSVC extension, not part of C23.- Common uses: per-type function families (
vec_push_int,vec_push_double),typedefgeneration, hidden temporary variable names, token-based tables. - Empty arguments: an empty operand makes the result the other operand; this is well-defined.
- Combine with
#:#fieldinside the same macro is allowed. Use#__VA_ARGS__for lists. - Debugging is harder. Names built by pasting do not appear in the source, so grep and IDE navigation miss them. Keep generated names regular.
- Alternative:
_Genericpicks the right function by argument type without needing different spellings at the call site.
Related
- The # operator, #define, X macros
- Tutorial: Macros