c++ - Trying to understand the C preprocessor -


Why do these blocks of code get different results?

Some common codes:

  #define PART1PART2 works #define STRINGAFY0 (s) #s #define STRINGAFY1 (s) STRINGAFY0 (s)  < / Pre> 

Case 1:

  # Defined GLUU (A, B, C) A ## B ## C STRING AFI1 (GLUU (Part 1, Part 2, *) ) / Yield "PTI1 PTR2 *"  

Case 2:

  #define GLUE (a, b) ##b ## * STRINGAFY1 ( GLUE (PART1, PART2) / yield "work *"  

case 3:

  # defined GLUE (A, B) A ## B STRINGAFY1 (GLUE (PART1, PART2 *)) / yield "PART1PART2 *"  

I use MSVC ++ from VSNT2005 SP1 I am currently living.

EDIT: It is currently my belief that preprocessor works like this while expanding the macros: Step 1: - Move the body - ## Any white space around the operators Remove - Parsing the string, in this case an identifier is found which matches the name of a parameter: -If it is next to ## operator, then the identifier is replaced with the literal value due to the change parameter (y Ni is passed in the string) -If it is not ## next to the operator, then run this entire explanation process on the value of the parameter first, then replace the identifier with the result (Stranphi single '#' case Step 2: - Take that resulting string and parse it for any macros

Now, suppose that all 3 cases The result of the string as a result

PART1PART2 *

And so after step 2, the result of

works *

but very little Should result in less than one thing.

matters 1 and 2 are not defined behavior because you have a * (or just PART2 ) and * are enticing to paste in accordance with the Association rules of your preprocessor. Gum tries with. In your case it probably fails silently, which is one of the possible outcomes when things are undefined. After this, after the token PART1PART2 * will not be re-considered for macro expansion

  / usr / bin / gcc -O0 - G -std = c89 -pedantic -  e test- pregro test- preproduction.c: 16: 1: error: "PART1PART2" paste and "valid preprocessing token" works ""  < 

  • There are two problems with Summary 1 of your case.

    • Pasting two tokens that are not the result of a valid preprocessor token.
    • ## operator
    • In the case of the

    3 case, your compiler is giving the wrong result.

    1. STRINGAFY1
    2. To arguments Result PART1PART2 *
    3. should be expanded
    4. / Li>
    5. Result works
    6. then the STRINGAFY1
Has been passed for

Comments