Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

usage of `else` in macros

Tags:

c++

macros

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

like image 350
q0987 Avatar asked May 24 '12 19:05

q0987


People also ask

What does else do in VBA?

Else statement to define two blocks of executable statements: one block runs if the condition is True, and the other block runs if the condition is False.

How do you use if and else in Excel?

AND – =IF(AND(Something is True, Something else is True), Value if True, Value if False) OR – =IF(OR(Something is True, Something else is True), Value if True, Value if False) NOT – =IF(NOT(Something is True), Value if True, Value if False)

How many else if can you have in VBA?

The Else and ElseIf clauses are both optional. You can have as many ElseIf clauses as you want in a block If, but none can appear after an Else clause. Block If statements can be nested; that is, contained within one another.


1 Answers

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
like image 81
chris Avatar answered Oct 07 '22 04:10

chris