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

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

    For some reasons I can't comment on the first answer...

    Some of you showed macros with local variables, but nobody mentioned that you can't just use any name in a macro! It will bite the user some day! Why? Because the input arguments are substituted into your macro template. And in your macro examples you've use the probably most commonly used variabled name i.

    For example when the following macro

    #define FOO(X) do { int i; for (i = 0; i < (X); ++i) do_something(i); } while (0)
    

    is used in the following function

    void some_func(void) {
        int i;
        for (i = 0; i < 10; ++i)
            FOO(i);
    }
    

    the macro will not use the intended variable i, that is declared at the beginning of some_func, but the local variable, that is declared in the do ... while loop of the macro.

    Thus, never use common variable names in a macro!

提交回复
热议问题