Preprocessor Macros, Token Pasting & Side Effect Traps
“Macro text substitution, # and ## operators, and macro argument side-effect hazards.”
1.The C Preprocessor: Lexical Substitution
§ 5.1.The C Preprocessor operates before compilation, performing pure textual substitution without type checking:
1. #define Macro examPitfalls:
- Macros do not evaluate arguments before substitution!
- Classic bug: #define SQUARE(x) x x. Then SQUARE(2 + 3) expands to 2 + 3 2 + 3 = 2 + 6 + 3 = 11, NOT 25!
- Correct rule: Always wrap both arguments and the entire macro in parentheses: #define SQUARE(x) ((x) * (x)).
2. Side Effect Hazard:
- If SQUARE(i++) is used, it expands to ((i++) * (i++)), incrementing i TWICE (Undefined Behavior)!
3. Stringification (#) & Token Pasting (##):
- #x: Converts macro argument x into a string literal "x".
- x ## y: Concatenates tokens x and y into a single combined identifier xy.
Worked example: why macros need parentheses
SQ(2 + 3) becomes 2 + 3 * 2 + 3.
Multiplication first: 2 + 6 + 3.
((2 + 3) * (2 + 3)).
Practice: test yourself
Original practice questions in the GATE style, with worked explanations. Not past-paper questions.
#define DOUBLE(x) x + x What is 3 * DOUBLE(2)?
When are macros expanded?
What does #ifndef HEADER_H / #define HEADER_H / … / #endif do in a header file?
Primary Academic References & Exam Sources
Every concept in Notes From a B.Tech Brain is synthesized from authoritative academic texts, seminal peer-reviewed research, verified exam archives, and renowned university lectures.
Curated for clarity, rigorous numerical solving, and semester excellence:
Systematic beginner-to-advanced C with clear examples.
Clear step-by-step C explanations — great for semester lab preparation.