Token pasting (##) in macros: what does this program print? #include<stdio.h> #define FUN(i, j) i##j int main() { int va1 = 10; int va12 = 20; printf("%d\n", FUN(va1, 2)); return 0; }

Difficulty: Easy

Correct Answer: 20

Explanation:


Introduction / Context:
Token pasting (##) concatenates tokens at preprocessing time to form a new token. This question checks whether you recognize that concatenating va1 with 2 yields the identifier va12, which is a different variable with its own value.


Given Data / Assumptions:

  • Variables: va1 = 10, va12 = 20.
  • Macro: #define FUN(i, j) i##j.
  • Call: FUN(va1, 2).


Concept / Approach:
The macro concatenates the tokens va1 and 2 to form va12. Since va12 exists and is initialized to 20, the printf prints 20. If va12 did not exist, this would be a compile-time error, showing that token pasting occurs before semantic checks.


Step-by-Step Solution:

Expand macro: FUN(va1, 2) → va12.Replace in printf: printf("%d\n", va12);.Value of va12 is 20 → prints 20.


Verification / Alternative check:
Try FUN(va, 12) with int va12 defined, or change the numbers to see compile failures when the pasted identifier is undefined.


Why Other Options Are Wrong:

10 prints va1, not the pasted name.“1020” would be string concatenation, which is not happening here.“12” is unrelated to the variable’s value.Compilation error does not occur because va12 is defined.


Common Pitfalls:
Confusing token pasting with runtime string operations; expecting arithmetic with 1 and 2 instead of identifier concatenation.


Final Answer:
20.

Discussion & Comments

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