Quant, Math & Computer Science Puzzles for Interview Preparation & Brain Teasing
A collection of ~225 Puzzles with Solutions (classified by difficulty and topic)

Sep 10, 2011

C++ Macro Concatenation

Source: http://www.gowrikumar.com
Problem: What is the output of the following C++ code?
  #include <stdio.h>
  #define f(a,b) a##b
  #define g(a)   #a
  #define h(a) g(a)

  int main()
  {
          printf("%s\n",h(f(1,2)));
          printf("%s\n",g(f(1,2)));
          return 0;
  }


Update (14 Sept 2011):

Solution posted in comments by Prathmesh Prabhu (CSE IITB 2010 Alumnus and Wisonsin Madison II-year Graduate Student)


2 comments:

  1. Output:
    12
    f(1,2)

    Reason: second line first. The macro g(a) uses stringification. The argument in stringification is *not* macro-expanded (or even evaluated) and hence f(1,2) remains as is. The macro h(a) on the other hand has another macro in the body, and the argument (a) is macro-expanded *before* the macro g is expanded.

    So the two macro expansions are...
    h(f(1,2))
    => eval)>
    => eval)>
    => eval
    => eval<#12>
    => "12"

    g(f(1,2))
    =>eval<#f(1,2)>
    =>"f(1,2)"

    ReplyDelete
  2. The reading material for this problem is:

    http://gcc.gnu.org/onlinedocs/cpp/Stringification.html#Stringification

    http://gcc.gnu.org/onlinedocs/cpp/Concatenation.html#Concatenation

    As pointed out by Prathmesh (A Rustle), the answer is 12 and f(1,2).

    I believe there is some problem in publishing Prathmesh's comment. Hence, reiterating:

    So the two macro expansions are...
    h(f(1,2))
    => h(1##2)
    => h(12)
    => g(12)
    => "12"

    g(f(1,2))
    => #f(1,2)
    => "f(1,2)"

    ReplyDelete