Can we remove parentheses around arguments in C macros definitions?

限于喜欢 提交于 2019-11-28 02:06:43

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.
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!