Pre-processor query

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Aftabpasha
    New Member
    • Oct 2008
    • 32

    #1

    Pre-processor query

    I've seen the following code snippet.
    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;
    }
    The output is
    Code:
    12
    f(1,2)
    I GUESS that in the first printf(), firstly, it is replacing h(f(1,2)) by g(f(1,2)), and then immediately in the same pass, it calculated its argument i.e. f(1,2), resulting in "12". Thus getting g("12") in place of h(f(1,2)). This g("12") results in a string "12".

    In short, in first printf()
    h(f(1,2)) >> g("12") >> "12"

    In the second printf(),
    g(f(1,2)) >> "f(1,2)"

    I'm not sure about this guesswork. Still some questions remain. Please put some light on it. How many passes does a C pre-processor performs? And exactly how it works? Please explain it.

    Thank you.
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    You guessed right: the # operator stringizes its operand, i.e. it puts double quotes around it. The ## operator 'glues' its operands together.

    The preprocessor expands macro definitions in the text. It keeps expanding macros as long as it finds any; to block recursion it won't expand a macro that is being expanded already.

    kind regards,

    Jos

    Comment

    • Aftabpasha
      New Member
      • Oct 2008
      • 32

      #3
      Thanks for replying.
      Still I've a confusion.

      Does a C Preprocessor work in multiple passes or in a single pass?

      Thanks.

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by Aftabpasha
        Thanks for replying.
        Still I've a confusion.

        Does a C Preprocessor work in multiple passes or in a single pass?

        Thanks.
        It uses a single pass and it rescans the text that results from macro expansion again and again as long as more macros to be expanded are found in that text.

        kind regards,

        Jos

        Comment

        • Aftabpasha
          New Member
          • Oct 2008
          • 32

          #5
          Thanks for fruitful reply.

          Comment

          Working...