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

前端 未结 8 1709
名媛妹妹
名媛妹妹 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.

    0 讨论(0)
  • 2021-02-02 14:03

    if introduces a statement, not an expression. Use the "ternary" (conditional) operator:

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

    Alternatively, make this an inline function:

    inline float sum_a(float x, float y)
    {
        if (x == 0 || y == 0)
            return 0;
        else
            return ((x * x) / (x + y)) * y;
    }
    

    This avoids the problem of multiple evaluation of x and/or y and is much more readable, but it does fix the types of x and y. You can also drop the inline and let the compiler decide whether inlining this function is worthwhile (inline is not a guarantee that it will perform inlining).

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