significance

Jul 22, 2011 at 4:57am
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);
Jul 22, 2011 at 5:08am
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);
Jul 22, 2011 at 12:59pm
Using break and continue is sloppy; while(0) or while(1) are just a consequences of it ;)
Jul 22, 2011 at 2:14pm
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.
Jul 22, 2011 at 2:25pm
closed account (1yR4jE8b)
@Disch
I'd rather just use goto instead of that monstrosity.
Jul 22, 2011 at 2:27pm
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.
Jul 23, 2011 at 11:22am
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
Jul 23, 2011 at 5:20pm
It is also very useful in macro expansions...
Topic archived. No new replies allowed.