Using Parentheses in Define Preprocessor Statements

前端 未结 4 1624
灰色年华
灰色年华 2020-12-06 13:59

So I was wondering when is to use

 #define xxx (yyy)

vs

 #define xxx  yyy

My project includes a files tha

相关标签:
4条回答
  • 2020-12-06 14:10

    By adding parentheses, you are forcing the argument inside the parentheses to be evaluated before the rest of the macro body, so if you had

    #define MULT(x, y) (x) * (y)
    // now MULT(3 + 2, 4 + 2) will expand to (3 + 2) * (4 + 2)
    

    It does not appear to affect your current case unless there is more to your macros.

    0 讨论(0)
  • 2020-12-06 14:21

    There is no difference in both. In first case XXX is replaced by yyy and by (yyy) is second case. The convention to use brackts is to avoid logical errors that may occur. For example you define addition function as:

    #define f(N) N+N 
    int a = f(5)*f(5)  
    

    Expected value is 10*10 = 100 , but output is 35 because at compile time is becomes

    int a = 5+5*5+5, so using operator preference rule, output changes.

    So parenthesis avoid these type of errors.

    0 讨论(0)
  • 2020-12-06 14:24

    An important thing to remember is that the preprocessor simply expands macros. For example, if you had the following lines:

    #define AD0_COMPARETIME_1    (AD0_ADMD_CT)
    #define AD0_COMPARETIME_2    AD0_ADMD_CT
    
    num_1 = AD0_COMPARETIME_1;
    num_2 = AD0_COMPARETIME_2;
    

    After the first expansion you'd have this:

    num_1 = (AD0_ADMD_CT);
    num_2 = AD0_ADMD_CT;
    

    And after the second expansion you'd have this:

    num_1 = ((IO_AD1.ADMD.bit.CT));
    num_2 = (IO_AD1.ADMD.bit.CT);
    

    A problem may arise, as stated in other answers, when an expression is expanded.

    0 讨论(0)
  • 2020-12-06 14:31

    It's very important if you have operators in your macro. For example:

    #define ADD(x,y) x + y
    ADD(1,2) * 3 /* Should be 9, is 7 */
    

    Should be:

    #define ADD(x,y) (x + y)
    ADD(1,2) * 3 /* 7 */
    

    These precedence problems also apply for the arguments, as @Gi Joe says, and need to be wrapped in parens for precedence.

    However, for a macro like:

    #define MAGICNUM 3
    

    It doesn't matter.

    0 讨论(0)
提交回复
热议问题