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

前端 未结 8 1716
名媛妹妹
名媛妹妹 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:40

    There are multiple problems with your macro:

    • it expands to a statement, so you cannot use it as an expression

    • the arguments are not properly parenthesized in the expansion: invoking this macro with anything but variable names or constants will produce problems.

    • the arguments are evaluated multiple times: if you invoke the macro with arguments that have side effects, such as SUM_A(a(), b()) or SUM_A(*p++, 2), the side effect will occur multiple times.

    To avoid all these problems, use a function, possibly defined as static inline to help the compiler optimize more (this is optional and modern compilers do this automatically):

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

    Notes:

    • this function uses floating point arithmetic, which the macro would not necessarily, depending on the actual types of its arguments.
    • the test does not prevent division by zero: SUM_A(-1, 1) still performs one.
    • division by zero is not necessarily a problem: with floating point arguments, it produces an Infinity or a NaN, not a runtime error.

提交回复
热议问题