Is there a good reason for always enclosing a define in parentheses in C?

后端 未结 9 1121
遇见更好的自我
遇见更好的自我 2020-12-01 02:33

Clearly, there are times where #define statements must have parentheses, like so:

#define WIDTH 80+20

int a = WIDTH * 2; // expect a==200 but a         


        
9条回答
  •  自闭症患者
    2020-12-01 03:12

    No. There is no case where #define WIDTH 100 can yield an unambiguous or "surprising" expansion. That's because it can only result in a single token being replaced by a single token.

    As you know, macro confusion ensues when a single token (e.g. WIDTH) results in multiple tokens (e.g. 80 + 20). As far as I can surmise, that's the only cause for the use of parentheses in substitutions and, as explored in my first paragraph, it doesn't apply here.

    However, this technical fact aside, it may still be a good practice. It promotes habit, and it also serves as a reminder if that macro ever gets modified to something more complex.

提交回复
热议问题