是否可以在#define中使用if语句? [英] Is it possible to use a if statement inside #define?
问题描述
我正在尝试使用以下公式制作一个宏:(a ^ 2 /(a + b))* b
,我想确保没有除以零。
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 ) )}
然后我在main中调用宏:
and then I call the macro inside main:
float a = 40, b = 10, result;
result = SUM_A(a, b);
printf("%f", result);
我尝试在if函数周围使用括号,但我在if语句之前一直遇到语法错误。我也尝试过使用return,但是我在某处读到了你不应该在define中使用它。
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.
推荐答案
你不能使用if语句,因为 #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 ) )}
这是错误的语法。
但另一种方法是使用三元运算符。将您的定义更改为
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.
这篇关于是否可以在#define中使用if语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!