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

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

提交回复
热议问题