5.1.27 · D3C Programming

Worked examples — Preprocessor directives — #define, #ifdef, #ifndef, #include guards

2,375 words11 min readBack to topic

The scenario matrix

Every problem this topic can pose falls into one of these case classes. The worked examples below are each tagged with the cell they cover, and together they hit every cell.

# Case class What can go wrong / what to watch Example that covers it
A Object-like macro, simple constant text swap, no arithmetic by preprocessor Ex 1
B Function-like macro, precedence danger missing parens change grouping Ex 2
C Function-like macro, side-effect / double-eval argument evaluated twice Ex 3
D #ifdef / #ifndef branch selection (defined) which text survives Ex 4
E #ifndef default value override external -D wins vs built-in default Ex 5
F Include guard — paste-twice degenerate case second paste deleted entirely Ex 6
G Degenerate / zero input to a macro empty arg, 0, macro-defined-as-nothing Ex 7
H Real-world word problem (cross-platform) choosing the right branch on a real target Ex 8
I Exam twist — trailing semicolon + nesting the classic arr[MAX;] and stacked conditions Ex 9
J Limiting case — macro that expands to another macro (chained) rescanning, recursion limits Ex 10
Figure — Preprocessor directives — #define, #ifdef, #ifndef, #include guards

Worked examples






Figure — Preprocessor directives — #define, #ifdef, #ifndef, #include guards





Recall Rapid self-test (cover the answers)

Ex1 RATE*8+2 ::: 42 Ex2 AREA(2+3,4) with w*h body ::: 14 (fix gives 20) Ex3 MAX2(i++,3) from i=5 gives m,i ::: m=6, i=7 (double evaluation) Ex5 with -DBUFFER_SIZE=1024 ::: buf has 1024 bytes Ex6 struct pasted with guard, included twice ::: appears once Ex8 NEWLINE on Linux ::: "\n" Ex9 fixed extra ::: 11 Ex10 TWICE(A) through chain ::: 14