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) 模式
基础教程推荐
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- c++ STL设置差异 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
