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
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).