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 SUM_A( x, y ) if( x == 0 || y == 0) { 0 } else { ( ( ( x * x ) / ( ( x ) + ( y ) ) ) * ( y ) )}
and then I call the macro inside main:
float a = 40, b = 10, result;
result = SUM_A(a, b);
printf("%f", result);
I’ve tried using brackets around the if function but I keep getting syntax errors before the if statement. I’ve also tried using return, but I read somewhere that you’re not supposed to use that in define.
You can not use if statement, because
#defineis interpret by the preprocessor, and the output would bewhich is wrong syntax.
But an alternative is to use ternary operator. Change your define to
Remember to always put your define between parentheses, to avoid syntax error when replacing.