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 myVar1#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 called6MAKE_FUNC(click)// Defines hover_handler the same way7MAKE_FUNC(hover)8 // Declares int myVar = 1009int CONCAT(my, Var) = 100;// Declares int totalCount = 5010int CONCAT(total, Count) = 50;11 // The generated names are ordinary variables: prints myVar: 10012printf("myVar: %d\n", myVar);// Prints totalCount: 5013printf("totalCount: %d\n", totalCount);// Calls the generated functions: prints click handler called, then hover handler called14click_handler();15hover_handler();Output
myVar: 100 totalCount: 50 click handler called hover handler called
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