What does ## in a #define mean?

后端 未结 6 2289
感情败类
感情败类 2020-12-05 22:47

What does this line mean? Especially, what does ## mean?

#define ANALYZE(variable, flag)     ((Something.##variable) & (flag))

Edit:

6条回答
  •  忘掉有多难
    2020-12-05 23:46

    One very important part is that this token concatenation follows some very special rules:

    e.g. IBM doc:

    • Concatenation takes place before any macros in arguments are expanded.
    • If the result of a concatenation is a valid macro name, it is available for further replacement even if it appears in a context in which it would not normally be available.
    • If more than one ## operator and/or # operator appears in the replacement list of a macro definition, the order of evaluation of the operators is not defined.

    Examples are also very self explaining

    #define ArgArg(x, y)          x##y
    #define ArgText(x)            x##TEXT
    #define TextArg(x)            TEXT##x
    #define TextText              TEXT##text
    #define Jitter                1
    #define bug                   2
    #define Jitterbug             3
    

    With output:

    ArgArg(lady, bug)   "ladybug"
    ArgText(con)    "conTEXT"
    TextArg(book)   "TEXTbook"
    TextText    "TEXTtext"
    ArgArg(Jitter, bug)     3
    

    Source is the IBM documentation. May vary with other compilers.

    To your line:

    It concatenates the variable attribute to the "Something." and adresses a variable which is logically anded which gives as result if Something.variable has a flag set.

    So an example to my last comment and your question(compileable with g++):

    // this one fails with a compiler error
    // #define ANALYZE1(variable, flag)     ((Something.##variable) & (flag))
    // this one will address Something.a (struct)
    #define ANALYZE2(variable, flag)     ((Something.variable) & (flag))
    // this one will be Somethinga (global)
    #define ANALYZE3(variable, flag)     ((Something##variable) & (flag))
    #include 
    using namespace std;
    
    struct something{
    int a;
    };
    
    int Somethinga = 0;
    
    int main()
    {
    something Something;
    Something.a = 1;
    
    if (ANALYZE2(a,1))
        cout << "Something.a is 1" << endl;
    if (!ANALYZE3(a,1))
        cout << "Somethinga is 0" << endl;
            return 1;
    };
    

提交回复
热议问题