PROGRAMMING IN C/Student Engineering Notebook
Page 09·notes
PREPROCESSOR DIRECTIVES, MACROS & FILE I/O—~28 MIN READ

Preprocessor Macros, Token Pasting & Side Effect Traps

“Macro text substitution, # and ## operators, and macro argument side-effect hazards.”

1.The C Preprocessor: Lexical Substitution

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 NUMERICAL · STUDENT DERIVATION✎ Key Takeaway: Parenthesise every parameter and the whole body. Arguments with side effects, like SQ(i++), are still evaluated twice.

Worked example: why macros need parentheses

Problem Statement:
#define SQ(x) x x What is SQ(2 + 3)? And with #define SQ(x) ((x) (x))?
Step 1: Plain text substitution

SQ(2 + 3) becomes 2 + 3 * 2 + 3.

Step 2: Evaluate

Multiplication first: 2 + 6 + 3.

11
Step 3: The fixed macro

((2 + 3) * (2 + 3)).

25
Final Answer:11 with the unsafe macro, 25 with the parenthesised one
STUDENT PRACTICE · CONCEPT DRILL

Practice: test yourself

Original practice questions in the GATE style, with worked explanations. Not past-paper questions.

Problem 1 · TRICKY

#define DOUBLE(x) x + x What is 3 * DOUBLE(2)?

Problem 2 · FOUNDATION

When are macros expanded?

Problem 3 · GATE-LEVEL

What does #ifndef HEADER_H / #define HEADER_H / … / #endif do in a header file?

SOURCE TRANSPARENCY & CITATIONS

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 University Lecture Series
The C Programming Language (2nd Edition) ·
LECTURE SERIES
RECOMMENDED YOUTUBE EDUCATORS & FULL-COURSE PLAYLISTS

Curated for clarity, rigorous numerical solving, and semester excellence:

Neso Academy · C Programming Full Course↗Instructor: Neso Academy · Covers: Data types, pointers, arrays, functions, recursion, file I/O

Systematic beginner-to-advanced C with clear examples.

Open YouTube↗
Jenny's Lectures CS/IT · C Programming↗Instructor: Jenny's Lectures · Covers: Arrays, strings, pointers, structures, file handling, preprocessor

Clear step-by-step C explanations — great for semester lab preparation.

Open YouTube↗