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

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

    As Blagovest Buyukliev said:

    The define consists of a single token (one operand only, no operators), the parentheses are not needed because a single token (such as 100) is an indivisible atom when lexing and parsing.

    But I would recommend the following rules when it comes to macros:

    1. Avoid function like macros @see Lundin's comment.

    If you want to use function like macros badly consider the following 2 rules:

    1. Always use brackets for arguments in macros
    2. Only use an macro argument once

    Why rule 1.? (To keep the order of the operations correct)

    #define quad(x) (x*x)
    int a = quad(2+3);
    

    will expand to:

    int a = (2+3*2+3);
    

    Why rule 2.? (To ensure a side effect is only applied once)

    #define quad(x) (x*x)
    int i = 1;
    int a = quad(i++);
    

    will expand to:

    int a = i++ * i++;
    

提交回复
热议问题