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
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: