Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do { ... } while (0) — what is it good for? [duplicate]

Tags:

c

loops

Possible Duplicate:
Why are there sometimes meaningless do/while and if/else statements in C/C++ macros?

I've been seeing that expression for over 10 years now. I've been trying to think what it's good for. Since I see it mostly in #defines, I assume it's good for inner scope variable declaration and for using breaks (instead of gotos.)

Is it good for anything else? Do you use it?

like image 920
gilm Avatar asked Nov 02 '08 21:11

gilm


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.

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 does while 1 mean in C programming?

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.


2 Answers

It's the only construct in C that you can use to #define a multistatement operation, put a semicolon after, and still use within an if statement. An example might help:

#define FOO(x) foo(x); bar(x)  if (condition)     FOO(x); else // syntax error here     ...; 

Even using braces doesn't help:

#define FOO(x) { foo(x); bar(x); } 

Using this in an if statement would require that you omit the semicolon, which is counterintuitive:

if (condition)     FOO(x) else     ... 

If you define FOO like this:

#define FOO(x) do { foo(x); bar(x); } while (0) 

then the following is syntactically correct:

if (condition)     FOO(x); else     .... 
like image 142
Greg Hewgill Avatar answered Sep 22 '22 08:09

Greg Hewgill


It is a way to simplify error checking and avoid deep nested if's. For example:

do {   // do something   if (error) {     break;   }   // do something else   if (error) {     break;   }   // etc.. } while (0); 
like image 42
Jere.Jones Avatar answered Sep 20 '22 08:09

Jere.Jones