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

后端 未结 9 1103
遇见更好的自我
遇见更好的自我 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:04

    Sometimes you have to write code not with the current caveats in mind, but with the ones of next time it is going to be edited.

    Right now your macro is a single integer. Imagine someone editing it in the future. Let's say they are not you, but someone who is less careful or in more in a hurry. The parentheses are there to remind people to put any modifications within them.

    This kind of thinking is a good habit in C. I personally write code in a style which some people might find "redundant", with things like this but especially with regards to error handling. Redundancy is for maintainability and composability of future editings.

提交回复
热议问题