Can we remove parentheses around arguments in C macros definitions?

前端 未结 2 1619
时光取名叫无心
时光取名叫无心 2020-12-07 03:49

From http://c-faq.com/style/strcmp.html, I learned the following convenience macro:

#define Streq(s1, s2) (strcmp((s1), (s2)) == 0)

I want

相关标签:
2条回答
  • 2020-12-07 04:04

    Here's a relatively dumb example, but it does have a different result:

    #define Streq(s1, s2) (strcmp((s1), (s2)) == 0)
    #define MyStreq(s1, s2) (strcmp(s1, s2) == 0)
    #define s1 "foo", "blah"
    
    int main() {
        Streq(s1, "blah"); // Compiles and compares equal.
        MyStreq(s1, "blah"); // Compiler error. Too many parameters.
    }
    
    0 讨论(0)
  • 2020-12-07 04:07

    Parentheses do sometimes matter, and it is a good idea to unconditionally insert them. Consider the following poor macro:

    #define OP(a, b) (a * b) /* BAD */
    

    Invoked as OP(x + 1, y + 1) it will expand to x + 1 * y + 1, breaking the intended grouping. Parentheses prevent this problem.

    If you read a macro definition with parentheses around each argument use, the author certainly had this issue in mind - even if those parens happen to be redundant for that macro.

    0 讨论(0)
提交回复
热议问题