Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use do { ... } while (FALSE); in C++ outside of macros [duplicate]

Tags:

c++

Possible Duplicate:
Are do-while-false loops common?

Is there a reason to have code like:

do {
    // a lot of code that only needs to be run once
} while (FALSE);

when the code isn't defining a macro? I know it's a trick when it comes to macros, but is there a reason for it in normal code?

like image 219
Anon Avatar asked Jan 07 '11 14:01

Anon


2 Answers

Well, it does allow you to use the break; (or continue) keyword for early exit if you have a need for that for some reason. That would be kinda ugly though. I'd really rather see it moved into its own routine, with the early exit implemented via a return; statement.

like image 98
T.E.D. Avatar answered Oct 05 '22 23:10

T.E.D.


Well one reason for it would be if you want to break out at some point.

i.e.

do
{
   //some code that should always execute...

   if ( condition )
   {
      //do some stuff
      break;
   }

   //some code that should execute if condition is not true

   if ( condition2 )
   {
       //do some more stuff
       break;
   }

   //further code that should not execute if condition or condition2 are true

}
while(false);

In certain situations the resulting code is a little bit more clear / easier to understand if written as above.

like image 27
ds27680 Avatar answered Oct 06 '22 00:10

ds27680