Is it possible to use a if statement inside #define?

前端 未结 8 1814
名媛妹妹
名媛妹妹 2021-02-02 13:34

I\'m trying to make a macro with the following formula: (a^2/(a+b))*b, and I want to make sure that the there will be no dividing by zero.

#define          


        
8条回答
  •  轮回少年
    2021-02-02 13:57

    You can not use if statement, because #define is interpret by the preprocessor, and the output would be

     result=if( x == 0 || y == 0) { 0 } else { ( ( ( x * x ) / ( ( x ) + ( y ) ) ) * ( y ) )}
    

    which is wrong syntax.

    But an alternative is to use ternary operator. Change your define to

    #define SUM_A( x, y )  ((x) == 0 || (y) == 0 ? 0 : ( ( ( (x) * (x) ) / ( ( x ) + ( y ) ) ) * ( y ) ))
    

    Remember to always put your define between parentheses, to avoid syntax error when replacing.

提交回复
热议问题