Why do I need double layer of indirection for macros?

后端 未结 5 1525
执念已碎
执念已碎 2020-11-29 02:42

At: C++ FAQ - Miscellaneous technical issues - [39.6] What should be done with macros that need to paste two tokens together?

Could someone explain to me wh

5条回答
  •  长情又很酷
    2020-11-29 03:35

    Chris Dodd has an excellent explanation for the first part of your question. As for the second part, about the definition sequence, the short version is that #define directives by themselves are not evaluated at all; they are only evaluated and expanded when the symbol is found elsewhere in the file. For example:

    #define A a  //adds A->a to the symbol table
    #define B b  //adds B->b to the symbol table
    
    int A;
    
    #undef A     //removes A->a from the symbol table
    #define A B  //adds A->B to the symbol table
    
    int A;
    

    The first int A; becomes int a; because that is how A is defined at that point in the file. The second int A; becomes int b; after two expansions. It is first expanded to int B; because A is defined as B at that point in the file. The preprocessor then recognizes that B is a macro when it checks the symbol table. B is then expanded to b.

    The only thing that matters is the definition of the symbol at the point of expansion, regardless of where the definition is.

提交回复
热议问题