Token Pasting Macro in C

Level 5317 keystrokes

Uses the ## operator to paste tokens into new names at preprocessing time: CONCAT(my, Var) declares myVar, and MAKE_FUNC(click) defines click_handler, whose message comes from #name. It prints myVar: 100, totalCount: 50, click handler called and hover handler called.

C code

// ## pastes two tokens into one: CONCAT(my, Var) becomes myVar
1#define CONCAT(a, b) a ## b
// Generates a whole function: name ## _handler builds its name
// #name turns the argument into a string literal, e.g. "click"
2#define MAKE_FUNC(name) void name ## _handler() { \
3 printf(#name " handler called\n"); \
4}
5
// Defines void click_handler(), which prints click handler called
6MAKE_FUNC(click)
// Defines hover_handler the same way
7MAKE_FUNC(hover)
8
// Declares int myVar = 100
9int CONCAT(my, Var) = 100;
// Declares int totalCount = 50
10int CONCAT(total, Count) = 50;
11
// The generated names are ordinary variables: prints myVar: 100
12printf("myVar: %d\n", myVar);
// Prints totalCount: 50
13printf("totalCount: %d\n", totalCount);
// Calls the generated functions: prints click handler called, then hover handler called
14click_handler();
15hover_handler();

Output

myVar: 100
totalCount: 50
click handler called
hover handler called
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • (× 12
  • )× 12
  • ;× 7
  • #× 7
  • _× 6
  • "× 6
  • ,× 5
  • \× 5
  • :× 2
  • %× 2

More C examples at level 5

← C typing practice