Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-statement Macros in C++

Tags:

c++

macros

In C++, is it possible to make a multi-statement macro with nested if statements inside of it like the one below? I've been attempting it for a while now and I'm getting a scope issue for the second if statement not being able to see 'symbol'. Maybe I need to understand macros further.

#define MATCH_SYMBOL( symbol, token)
     if(something == symbol){
          if( symbol == '-'){
          }else if (symbol != '-'){
          }
     other steps;
     }
like image 538
Jesse O'Brien Avatar asked Nov 27 '22 23:11

Jesse O'Brien


2 Answers

For a multi-line macro you need to add a \ character to the end of all but the last line to tell the macro processor to continue parsing the macro on the next line, like so:

#define MATCH_SYMBOL( symbol, token) \
     if(something == symbol){        \
          if( symbol == '-'){        \
          }else if (symbol != '-'){  \
          }                          \
     other steps;                    \
     }

Right now, it's trying to interpret it as a 1-line macro and then some actual code at the top of your file, which isn't what you want:

#define MATCH_SYMBOL( symbol, token)

// and then... wrongly thinking this is separate...

 if(something == symbol){ // symbol was never defined, because the macro was never used here!
      if( symbol == '-'){
      }else if (symbol != '-'){
      }
 other steps;
 }
like image 90
Amber Avatar answered Dec 10 '22 18:12

Amber


If you're using C++ you should avoid using macros altogether. They are not type-safe, they're not namespace-aware, they're hard to debug and just they're plain messy.

If you need a type-independent function, use templates:

template <typename T>
bool match_symbol(T symbol, T token) {
    if(something == symbol){
        if( symbol == '-'){
        }else if (symbol != '-'){
        }
    ...

or if the parameters can be different types:

template <typename T, typename V>
bool match_symbol(T symbol, V token) {
    if(something == symbol){
        if( symbol == '-'){
        }else if (symbol != '-'){
        }
    ...
like image 24
Tim Sylvester Avatar answered Dec 10 '22 18:12

Tim Sylvester