significance

Hi,

I have seen in many of open source codes the do-while(0). Can anybody let me know when this is useful and whats the significance of constructing such code?

do
{
...........
...........
}while(0);
It allows you to mimic a goto command. Personally I find it pretty sloppy:

1
2
3
4
5
6
7
8
9
10
11
12
do
{
  if(something)
  {
    continue;  // exits the loop
  }

  if(something_else)
  {
    break;  // also exits the loop
  }
}while(0);
Using break and continue is sloppy; while(0) or while(1) are just a consequences of it ;)
The do-while construct is useful when you want to run something at least once, and in this case, only once, because the while( 0 ) will end the do-while.
closed account (1yR4jE8b)
@Disch
I'd rather just use goto instead of that monstrosity.
rapidcoder wrote:
Using break and continue is sloppy;


It's true they can be sloppy, that isn't to say they're always sloppy. Often times they are very practical.

kooth wrote:
The do-while construct is useful when you want to run something at least once, and in this case, only once, because the while( 0 ) will end the do-while.


The thing is, if you want something to run once and only once, you don't need any loop at all. Which is why the do{}while(0); construct is kind of ridiculous.
Hi All,

Thank you for the participation.

I found links on this.

http://c2.com/cgi/wiki?TrivialDoWhileLoop
http://stackoverflow.com/questions/154136/why-are-there-sometimes-meaningless-do-while-and-if-else-statements-in-c-c-macr


So one reason is what Disch said about.
One more reason is to keep code tidy, i.e. to allow semicolon after MACRO in some cases.

Refer links for details
It is also very useful in macro expansions...
Topic archived. No new replies allowed.