Macros of several statements in C ++

In C ++, is it possible to make a macro with several statements with nested if statements inside it, as shown below? I have been trying to do this for a while, and I am getting a scope problem for the second if statement, which the symbol cannot see. Perhaps I still need to understand macros.

#define MATCH_SYMBOL( symbol, token)
     if(something == symbol){
          if( symbol == '-'){
          }else if (symbol != '-'){
          }
     other steps;
     }
+3
source share
7 answers

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

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

, , :

#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;
 }
+11

++, . , , , .

, :

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

:

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

, .

, :

if (foo)
   function();
else
   otherstuff();

, function , :

if (foo)
   if (something) { /* ... */ }
   else           { /* ... */ }; // <-- note evil semicolon!
else
   otherstuff();

, () , , :

#define MATCH_SYMBOL(symbol, token)    \
    do                                 \
    {                                  \
       if(something == symbol)         \
       {                               \
          if( symbol == '-')           \
          {                            \
          }                            \
          else if (symbol != '-')      \
          {                            \
          }                            \
          other steps;                 \
       }                               \
    }                                  \
    while (0) // no semicolon here

, "statement" MATCH_SYMBOL(a, b) , . .

, , , . Linux, .

+4

(\) , .

+1

++:

inline void MATCH_SYMBOL(const Symbol& symbol, const Token& token) {
    /* ... */
    if (something == symbol) {

        if ('-' == symbol) {
        /* ... */
        }
        else if ('-' != symbol) {
        /* ... */
        }
    }
    /* ...other steps... */
}
+1

, , .

?
MATCH_SYMBOL(Sym const & symbol, Tok const & token)
{
    ...
}
0

,

#define MATCH_SYMBOL( symbol, token) match_symbol(symbol,token)
0

Source: https://habr.com/ru/post/1724444/


All Articles