Why use apparently meaningless do-while and if-else statements in macros?

前端 未结 9 1924
轻奢々
轻奢々 2020-11-21 04:00

In many C/C++ macros I\'m seeing the code of the macro wrapped in what seems like a meaningless do while loop. Here are examples.

#define FOO(X         


        
9条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-21 04:45

    Jens Gustedt's P99 preprocessor library (yes, the fact that such a thing exists blew my mind too!) improves on the if(1) { ... } else construct in a small but significant way by defining the following:

    #define P99_NOP ((void)0)
    #define P99_PREFER(...) if (1) { __VA_ARGS__ } else
    #define P99_BLOCK(...) P99_PREFER(__VA_ARGS__) P99_NOP
    

    The rationale for this is that, unlike the do { ... } while(0) construct, break and continue still work inside the given block, but the ((void)0) creates a syntax error if the semicolon is omitted after the macro call, which would otherwise skip the next block. (There isn't actually a "dangling else" problem here, since the else binds to the nearest if, which is the one in the macro.)

    If you are interested in the sorts of things that can be done more-or-less safely with the C preprocessor, check out that library.

提交回复
热议问题