做 while(false) 模式

2022-01-11 00:00:00 macros c++

可能重复:
为什么有时会有C/C++ 宏中的 do/while 和 if/else 语句毫无意义?

为什么下面的宏中需要do while(false)?

Why is the do while(false) necessary in the macros below?

#define LOG(message, ...) 
do { 
Lock<MutualExclusion> lock (logMutex); 

 .... a lot of code ...
} while (false)

我认为它没有任何功能用途.我是否忽略了什么?

I dont think it serves any functional purpose. Am I overlooking something?

推荐答案

它将一个块变成一个语句.如果您只使用一个块(即包含在 {} 中的代码)可能会发生奇怪的事情,例如

It turns a block into a single statement. If you just use a block (i.e. code enclosed in {}) strange things can happen, for example

#define STUFF() 
  { do_something(); do_something_else(); }

if (cond)
    STUFF();
else
    //...

额外的分号会破坏语法.do {} while(false) 是一个单独的语句.

the extra semi-colon breaks the syntax. The do {} while(false) instead is a single statement.

您可以找到有关此和其他宏技巧的更多信息这里.

You can find more about this and other macro tricks here.

相关文章