Multi-statement Macros in C++

前端 未结 7 1365
轻奢々
轻奢々 2021-01-19 08:00

In C++, is it possible to make a multi-statement macro with nested if statements inside of it like the one below? I\'ve be

7条回答
  •  爱一瞬间的悲伤
    2021-01-19 08:49

    Note that some of the answers here have a problem.

    For example, for a normal statement you can do this:

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

    If you followed some of the suggestions here, but if replace function with a macro, it might expand to:

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

    So a common (ugly) hack that people do to avoid this is:

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

    This is so that the "statement" MATCH_SYMBOL(a, b) can end with a semicolon just like a normal statement. You also have braces around the multiple statements.

    If you think nobody's crazy enough to use this technique, think again. It's very common in the Linux kernel, for example.

提交回复
热议问题