Possible Duplicates:
Do-While and if-else statements in C/C++ macros
do { … } while (0) — what is it good for?
I'm reading the linux kernel and I found many macros like this:
#define INIT_LIST_HEAD(ptr) do { \ (ptr)->next = (ptr); (ptr)->prev = (ptr); \ } while (0)
Why do they use this rather than define it simply in a {}?
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.
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.
The while(1) acts as an infinite loop that runs continually until a break statement is explicitly issued. The while(0) loop means that the condition available to us will always be false.
The while(1) or while(any non-zero value) is used for infinite loop. There is no condition for while. As 1 or any non-zero value is present, then the condition is always true. So what are present inside the loop that will be executed forever.
You can follow it with a semicolon and make it look and act more like a function. It also works with if/else clauses properly then.
Without the while(0), your code above would not work with
if (doit) INIT_LIST_HEAD(x); else displayError(x);
since the semicolon after the macro would "eat" the else clause, and the above wouldn't even compile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With