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

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

    When code defines only a number, @Alexander Gessler well answers the question.

    Yet many coders do not notice the unary operators in the following:

    #define TEMPERATURE1M (-1)
    #define TEMPERATURE1P (+1)
    

    When code uses a #define that employs an operator, enclosing () insures expected numeric results and precedence.

    #define TEMPERATURE_WITH  (-1)
    #define TEMPERATURE_WITHOUT -1
    
    // Consider how these will compile
    int w  = 10-TEMPERATURE_WITH;
    int wo = 10-TEMPERATURE_WITHOUT;  // May not compile
    

    The last line of code may compile given C99 semantic changes @Olaf

提交回复
热议问题