Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the use of do while(0) when we define a macro? [duplicate]

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 {}?

like image 626
amazingjxq Avatar asked May 29 '09 00:05

amazingjxq


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 the difference between while 0 and while 1?

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.

What is meant by while 1 in C?

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.


Video Answer


1 Answers

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.

like image 59
SPWorley Avatar answered Sep 21 '22 19:09

SPWorley