0

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’
Lundin
  • 195,001
  • 40
  • 254
  • 396
Yves
  • 11,597
  • 17
  • 83
  • 180
  • 8
    Forget the macro for a minute. Just try `(b == false ? return 1 : ())` and you'll see that it doesn't work. Once you get something that *does* work, then you can obfuscate it with a macro. – user3386109 Jun 12 '19 at 07:20
  • Your `TEST` macro is a ternary expression and would result in something like `b == false ? return 1 : ()` which is not allowed. Why not just define your macro as `if (x == false) xxx 1` – derpirscher Jun 12 '19 at 07:21
  • Note that having jump statements hidden in macros is very bad design. You might want to reconsider your approach. – user694733 Jun 12 '19 at 07:33
  • 2
    Why would you ever want to write such a dirty macro? This is a "XY problem", what's the actual problem you are trying to solve with this macro? – Lundin Jun 12 '19 at 07:50

2 Answers2

5

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.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • Bare if statements in macros are problematic. Macro should be wrapped at least in `do { ... } while(0)`. – user694733 Jun 12 '19 at 07:31
  • 1
    @user694733 Those who have the good habit of always using {} after every single if statements don't have such bugs. And need not worry about hacks so as do-while(0). This is why the requirement of always using do-while(0) for macros was dropped in MISRA-C, since they already require that you always use compound statements, making do-while(0) not only superfluous, but actively harmful. – Lundin Jun 12 '19 at 07:48
0

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;
user6556709
  • 1,272
  • 8
  • 13