Yves
Yves

Reputation: 12431

How to use a "return" as a macro in a ternary operation?

I have a c++ code as below:

#define xxx return

int main()
{
    xxx 0;
}

It works as expected.

Now I change the code like this:

#define xxx return
#define TEST(X) ((X) == (false) ? (xxx 1) : ())

int main()
{
    bool b = false;
    TEST(b);
    return 0;
}

In a word, I want to return 1 if b is false. But I get the error:

error: expected primary-expression before ‘return’

Upvotes: 0

Views: 270

Answers (2)

return is a statement, and not an expression. And all three operands of ?: must be expressions only. The return keyword can't appear in any of them, expanded from a macro or not.

A macro that would work in your specific example would be a simple

#define TEST(X) if((X) == (false)) xxx 1

Though, if you mess around with macros be wary of the dangling else problem and proof the above against it.

Upvotes: 6

user6556709
user6556709

Reputation: 1270

You can't have a return statement inside the ternary operator. You need to use an ordinary if.

#define TEST(X) if ((X)  == false) return 1;

Upvotes: 0

Related Questions