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

前端 未结 9 1992
轻奢々
轻奢々 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 05:01

    While it is expected that compilers optimize away the do { ... } while(false); loops, there is another solution which would not require that construct. The solution is to use the comma operator:

    #define FOO(X) (f(X),g(X))
    

    or even more exotically:

    #define FOO(X) g((f(X),(X)))
    

    While this will work well with separate instructions, it will not work with cases where variables are constructed and used as part of the #define :

    #define FOO(X) (int s=5,f((X)+s),g((X)+s))
    

    With this one would be forced to use the do/while construct.

提交回复
热议问题