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

前端 未结 9 1937
轻奢々
轻奢々 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 04:53

    Explanation

    do {} while (0) and if (1) {} else are to make sure that the macro is expanded to only 1 instruction. Otherwise:

    if (something)
      FOO(X); 
    

    would expand to:

    if (something)
      f(X); g(X); 
    

    And g(X) would be executed outside the if control statement. This is avoided when using do {} while (0) and if (1) {} else.


    Better alternative

    With a GNU statement expression (not a part of standard C), you have a better way than do {} while (0) and if (1) {} else to solve this, by simply using ({}):

    #define FOO(X) ({f(X); g(X);})
    

    And this syntax is compatible with return values (note that do {} while (0) isn't), as in:

    return FOO("X");
    

提交回复
热议问题