What does ## in a #define mean?

后端 未结 6 2282
感情败类
感情败类 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:27

    A little bit confused still. What will the result be without ##?

    Usually you won't notice any difference. But there is a difference. Suppose that Something is of type:

    struct X { int x; };
    X Something;
    

    And look at:

    int X::*p = &X::x;
    ANALYZE(x, flag)
    ANALYZE(*p, flag)
    

    Without token concatenation operator ##, it expands to:

    #define ANALYZE(variable, flag)     ((Something.variable) & (flag))
    
    ((Something. x) & (flag))
    ((Something. *p) & (flag)) // . and * are not concatenated to one token. syntax error!
    

    With token concatenation it expands to:

    #define ANALYZE(variable, flag)     ((Something.##variable) & (flag))
    
    ((Something.x) & (flag))
    ((Something.*p) & (flag)) // .* is a newly generated token, now it works!
    

    It's important to remember that the preprocessor operates on preprocessor tokens, not on text. So if you want to concatenate two tokens, you must explicitly say it.

提交回复
热议问题