Two-level stringification in C macros: what does this program print?
#include
#define str(x) #x
#define Xstr(x) str(x)
#define oper multiply
int main()
{
char *opername = Xstr(oper);
printf("%s
", opername);
return 0;
}
-
AError during macro substitution
-
BError: invalid reference in macro
-
Cmultiply
-
DNo output
-
E"oper"
Answer
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) #xand#define Xstr(x) str(x)- Printing
opernamewithprintf.
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.