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) 模式
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
