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