Advanced Preprocessor Tricks
Learn how to use advanced preprocessor features such as stringizing (#), token pasting (##), and multi-line macros to generate flexible code and write safer, more maintainable macros for debugging and configuration.
As programs grow in size and complexity, macros are often used to support debugging, manage configuration, and reduce repetitive code. Beyond simple #define replacements and conditional compilation, the C preprocessor provides advanced operators that allow macros to generate strings, construct new identifiers, and expand safely into multiple statements.
In this lesson, we explore the stringizing (#) and token-pasting (##) operators, multi-line macros, and best practices for writing safer and more maintainable macros.
Stringizing operator (#)
The stringizing operator (#) converts a macro argument into a string literal. This conversion happens during preprocessing, before the program is compiled. It avoids manually writing the variable name as a string and keeps debugging output consistent.
Consider the following macro: #define PRINT_VAR(x) printf(#x " = %d\n", x). Let's see it in action: