Two-level stringification in C macros: what does this program print? #include<stdio.h> #define str(x) #x #define Xstr(x) str(x) #define oper multiply int main() { char *opername = Xstr(oper); printf("%s\n", opername); return 0; }

Difficulty: Easy

Correct Answer: multiply

Explanation:


Introduction / Context:
This checks knowledge of macro stringification and why a two-level macro is needed to stringify another macro’s replacement text instead of its name. It is a classic pattern used in build-time banners and generated identifiers.


Given Data / Assumptions:

  • #define oper multiply (token replacement)
  • #define str(x) #x and #define Xstr(x) str(x)
  • Printing opername with printf.


Concept / Approach:
Single-level stringification str(oper) would yield the literal "oper". However, two-level expansion Xstr(oper) first expands oper to multiply, then stringifies to "multiply". Therefore, the program prints multiply (without quotes).


Step-by-Step Solution:

Expand outer macro: Xstr(oper) → str(oper).Before applying #, inner argument expands: oper → multiply.Stringify: str(multiply) → "multiply".Prints: multiply.


Verification / Alternative check:
Change oper to divide and recompile; you will see divide printed, proving two-step expansion occurs.


Why Other Options Are Wrong:

Errors would only occur with malformed macros; these are standard patterns.Printing "oper" would happen if you used str(oper) directly.


Common Pitfalls:
Expecting # to expand its argument before stringifying; it does not without the two-level trick.


Final Answer:
multiply.

More Questions from C Preprocessor

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion