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

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

    The above answers explain the meaning of these constructs, but there is a significant difference between the two that was not mentioned. In fact, there is a reason to prefer the do ... while to the if ... else construct.

    The problem of the if ... else construct is that it does not force you to put the semicolon. Like in this code:

    FOO(1)
    printf("abc");
    

    Although we left out the semicolon (by mistake), the code will expand to

    if (1) { f(X); g(X); } else
    printf("abc");
    

    and will silently compile (although some compilers may issue a warning for unreachable code). But the printf statement will never be executed.

    do ... while construct does not have such problem, since the only valid token after the while(0) is a semicolon.

提交回复
热议问题