Interview Q&A · C · 12 questions in this topic

Preprocessor, Headers & Linking — C Interview Q&A

All C topics

The build model interviewers love — macros done right, include guards, linkage, and static vs dynamic libraries. Part of Preprocessor & Build · 202 questions in the C bank.

What does the preprocessor do? What are the common directives?

Answer

#include pastes files, #define creates macros, #ifdef/#ifndef/#if/#elif/#else/#endif select code conditionally, #error aborts with a message, #pragma issues compiler hints, #line renumbers diagnostics. It runs before compilation as pure textual transformation with no C understanding.

Because it is textual, every macro bug is a substitution surprise — parenthesize and prefer language features where possible.

Example

Example.cc
#ifdef DEBUG
#define LOG(x) printf("DBG: %s\n", x)
#else
#define LOG(x) ((void)0)
#endif

How do you write safe function-like macros?

Answer

Parenthesize every parameter use and the whole body (precedence), wrap multi-statement macros in do { ... } while (0) (semicolon safety), avoid evaluating arguments twice (side-effect duplication), and prefer static inline functions, enums and consts where possible.

The do-while-0 wrapper makes the macro behave like one statement in if/else chains — without it, trailing else binds wrongly.

Example

Example.cc
#define MAX(a, b) ((a) > (b) ? (a) : (b)) /* parens everywhere */
#define LOG_HI() do { puts("hi"); } while (0) /* one-statement shape */

What are the `#` (stringize) and `##` (token-paste) operators?

Answer

# turns a macro argument into a string literal (#x becomes "x") — used for assertions and generated messages. ## concatenates tokens (a##b becomes ab) — used for generated identifiers and accessor families.

Both operate at expansion time on tokens, not values; overuse creates undebuggable identifier soup, so confine them to small, documented generator macros.

Example

Example.cc
#define STR(x) #x            /* STR(hi) -> "hi" */
#define FIELD(t, n) t n;      /* generator building blocks */
#define CAT(a, b) a##b        /* CAT(var, 1) -> var1 */

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits