Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "do { ... } while (0)" do exactly in kernel code? [duplicate]

Tags:

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) 
like image 496
grokus Avatar asked Mar 04 '10 17:03

grokus


People also ask

What is the purpose of do while 0?

You may see a do loop with the conditional expression set to a constant value of zero (0). This creates a loop that will execute exactly one time. This is a coding idiom that allows a multi-line macro to be used anywhere that a single statement can be used.

Why define while do?

The do while loop checks the condition at the end of the loop. This means that the statements inside the loop body will be executed at least once even if the condition is never true. The do while loop is an exit controlled loop, where even if the test condition is false, the loop body will be executed at least once.

What is do while loop in C?

ANSWER. The C do while statement creates a structured loop that executes as long as a specified condition is true at the end of each pass through the loop.

Why do macros use do while?

In conclusion, macros in Linux and other codebases wrap their logic in do/while(0) because it ensures the macro always behaves the same, regardless of how semicolons and curly-brackets are used in the invoking code.


1 Answers

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.

like image 105
OregonGhost Avatar answered Nov 20 '22 23:11

OregonGhost