By Yves


2019-06-12 07:17:23 8 Comments

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’

2 comments

@StoryTeller 2019-06-12 07:21:08

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.

@user694733 2019-06-12 07:31:55

Bare if statements in macros are problematic. Macro should be wrapped at least in do { ... } while(0).

@Lundin 2019-06-12 07:48:21

@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.

@user6556709 2019-06-12 07:21:51

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;

@user694733 2019-06-12 07:31:59

Bare if statements in macros are problematic. Macro should be wrapped at least in do { ... } while(0).

Related Questions

Sponsored Content

27 Answered Questions

[SOLVED] How do you set, clear, and toggle a single bit?

5 Answered Questions

76 Answered Questions

[SOLVED] How do I iterate over the words of a string?

  • 2008-10-25 08:58:21
  • Ashwin Nanjappa
  • 2124180 View
  • 2860 Score
  • 76 Answer
  • Tags:   c++ string split

21 Answered Questions

[SOLVED] What is the "-->" operator in C++?

7 Answered Questions

24 Answered Questions

[SOLVED] Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

31 Answered Questions

[SOLVED] How do I detect unsigned integer multiply overflow?

10 Answered Questions

2 Answered Questions

[SOLVED] How to initialize a vector in C++

Sponsored Content