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

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

    I don't think it was mentioned so consider this

    while(i<100)
      FOO(i++);
    

    would be translated into

    while(i<100)
      do { f(i++); g(i++); } while (0)
    

    notice how i++ is evaluated twice by the macro. This can lead to some interesting errors.

提交回复
热议问题