What does "do { ... } while (0)" do exactly in kernel code?
c, kernel, linux-kernel
Solution
It's always used in macros so that a semicolon is required after a call, just like when calling a regular function.
In your example, you have to write
__local_irq_save(1);
while
__local_irq_save(1)
would result in an error about a missing semicolon. This would not happen if the do while was not there. If it was just about scoping, a simple curly brace pair would suffice.
Problem
Possible Duplicates: 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 I have seen a lot of usages like this, previously I though that the programmer wanted to break out of a block of code easily. Why do we need a do { ... } while (0) loop here? Are we trying to tell the compiler something? For instance in Linux kernel 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) ```
Related problems
- C multi-line macro: do/while(0) vs scope block
- What's the use of do while(0) when we define a macro?
- Why use apparently meaningless do-while and if-else statements in macros?
- C multi-line macro: do/while(0) vs scope block
- What's the use of do while(0) when we define a macro?
- Why use apparently meaningless do-while and if-else statements in macros?