do while(false) pattern(做 while(false) 模式)
问题描述
可能重复:
为什么有时会有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.
这篇关于做 while(false) 模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:做 while(false) 模式


- STL 中有 dereference_iterator 吗? 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- C++ 协变模板 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 静态初始化顺序失败 2022-01-01