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

前端 未结 9 1965
轻奢々
轻奢々 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:40

    @jfm3 - You have a nice answer to the question. You might also want to add that the macro idiom also prevents the possibly more dangerous (because there's no error) unintended behavior with simple 'if' statements:

    #define FOO(x)  f(x); g(x)
    
    if (test) FOO( baz);
    

    expands to:

    if (test) f(baz); g(baz);
    

    which is syntactically correct so there's no compiler error, but has the probably unintended consequence that g() will always be called.

提交回复
热议问题