在宏中使用`else` [英] usage of `else` in macros
问题描述
我看到以下代码:
#define QL_REQUIRE(condition,message)\
if !(condition)){\
std :: ostringstream _ql_msg_stream; \
_ql_msg_stream<<信息; \
throw QuantLib :: Error(__ FILE __,__ LINE__,\
BOOST_CURRENT_FUNCTION,_ql_msg_stream.str()); \
} else
这是我们假设使用它的方式。
void testingMacros1(){
double x = 0.0;
QL_REQUIRE(x!= 0,Zero number!);
}
我假设 else
到最后有一些特殊的用法。
问题> else
这个宏定义?
谢谢
条件。它需要条件为 true
,否则它将抛出异常。如果是真的,你可以把大括号放在正常的如果
语句之后。
这个:
QL_REQUIRE(x!= 0,x不能为0)
{
y = 100 / x; //除以0是坏的
}
条件中的宏订阅,它失败,它将打印给定的消息。如果它不失败,你的大括号或单行形成else语句。当看看整个事情时,逻辑只是有点反转。当使用它,它就像一个 if
,但是当它把它,如果
和
pre>
assert(x!= 0&&x must not be 0);
y = 100 / x; // divide by 0 is bad
I have seen the following code:
#define QL_REQUIRE(condition,message) \
if (!(condition)) { \
std::ostringstream _ql_msg_stream; \
_ql_msg_stream << message; \
throw QuantLib::Error(__FILE__,__LINE__, \
BOOST_CURRENT_FUNCTION,_ql_msg_stream.str()); \
} else
This is how we suppose to use it.
void testingMacros1 (){
double x =0.0;
QL_REQUIRE (x!=0 ," Zero number !");
}
I assume the else
in the end has some special usage.
Question> What is the usage of else
appended in the end of this macros definition?
Thank you
The macro checks the condition. It needs the condition to be true
, or else it will throw an exception. If it's true, you'd put braces after like a normal if
statement.
You'd use it like this:
QL_REQUIRE (x != 0, "x must not be 0")
{
y = 100 / x; //dividing by 0 is bad
}
The macro subs in the condition, and if it fails, it will print the given message. If it doesn't fail, your braces or one-liner form the else statement. The logic is just a bit reversed when looking at the whole thing. When using it, it's like an if
, but when subbing it in, the if
and the else
sort of get reversed roles.
It's sort of like saying this:
assert (x != 0 && "x must not be 0");
y = 100 / x; //dividing by 0 is bad
这篇关于在宏中使用`else`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!