A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
The ## operator concatenates two preprocessing tokens into a single token. If you write prefix ## _suffix and invoke it as prefix(field), the result is field_suffix. This is how macros generate function names, variable names, and type names programmatically. It is used in serialization frameworks, test harnesses, and boilerplate-reduction macros. It is also one of the hardest preprocessor features to debug because the generated code does not exist until after preprocessing.
#include <stdio.h>#define DECLARE_COUNTER(name) int count_##name = 0#define INCREMENT(name) count_##name++#define PRINT_COUNT(name) printf("%s: %d\n", #name, count_##name)int main(void) {DECLARE_COUNTER(requests);DECLARE_COUNTER(errors);INCREMENT(requests);INCREMENT(requests);INCREMENT(requests);INCREMENT(errors);PRINT_COUNT(requests);PRINT_COUNT(errors);return 0;}
The -E output shows the expanded code. count_##name became count_requests and count_errors. The ## pasted the token count_ with the macro argument. The # operator (stringification) turned the argument into a string literal for the printf. Two operators working together: ## creates identifiers, # creates strings.
The # operator converts a macro argument to a string literal. #name in a macro body becomes "requests" when invoked with requests. This is how assertion messages include the expression text, how logging macros embed variable names, and how test frameworks print the values they are comparing. It only works on macro parameters. You cannot stringify arbitrary expressions.
Token pasting and stringification are the preprocessor's code generation tools. They eliminate boilerplate by generating repetitive declarations, registrations, and dispatch tables. Use them sparingly. The generated code is invisible to debuggers and error messages reference the macro invocation, not the expansion. Next: predefined macros and a practical log file use case.
Finish the lesson once you have worked through the material. This awards ★ 30 XP.