【发布时间】:2011-01-23 18:57:18
【问题描述】:
可能的重复:
What’s the use of do while(0) when we define a macro?
Why are there sometimes meaningless do/while and if/else statements in C/C++ macros?
C multi-line macro: do/while(0) vs scope block
我见过很多这样的用法,以前我认为程序员想轻松地跳出一段代码。为什么我们需要一个 do { ... } while (0) 循环?我们是想告诉编译器一些事情吗?
例如在 Linux 内核 2.6.25 中,include/asm-ia64/system.h
/*
* - clearing psr.i is implicitly serialized (visible by next insn)
* - setting psr.i requires data serialization
* - we need a stop-bit before reading PSR because we sometimes
* write a floating-point register right before reading the PSR
* and that writes to PSR.mfl
*/
#define __local_irq_save(x) \
do { \
ia64_stop(); \
(x) = ia64_getreg(_IA64_REG_PSR); \
ia64_stop(); \
ia64_rsm(IA64_PSR_I); \
} while (0)
【问题讨论】:
-
我认为你是对的。这创造了你可以突破的障碍。它还在堆栈上创建另一个框架,但在大多数情况下,它只会被优化掉。如需更多线索,请查看 ia64_* 的定义。它们可能是具有 break 语句或其他类型的嘲弄的宏。
-
要么全部做,要么不做
标签: c linux-kernel kernel