Question

I have compared gcc assembler output of

do{ 

//some code 

}while(0);

with

do{

//some code

 break; 
}while(1);

The output is equal, with or without optimization but..

It's always that way?

No experiment can prove theories, they can only show they are wrong

Was it helpful?

Solution

There is a slight difference:

do {
  // code
  if ( condition )
    continue;
  // code
  break;
} while(1);

Will restart the loop when condition is true, whereas in the } while(0); version, the continue will be equivalent to break.

If no continue is present, then they should produce exactly the same code.

OTHER TIPS

The forms are not equivalent. This is an infinite loop:

do {
    continue;
    break;
} while (1);

This isn't:

do {
    continue;
} while (0);

Edit: Upon reading various comments on the matter, I will admit that this answer is wrong. Sorry.

Instead of:

do{ 

//some code 

}while(0);

or:

do{

//some code

 break; 
}while(1);

I would just use:

//some code

I'm not 100% sure if you can do this in c++, but if you want to limit the scope of variables, and that is why you are doing this, just use curly braces by themselves:

{

 // Some Code

}

Markus' comment pointed me to this answer: the difference is when using continue keyword.

In this case:

int _tmain(int argc, _TCHAR* argv[])
{
    int i = 0;
    do {
        ++i;
        _tprintf(_T("Iteration %d\n"), i);
        if (i < 30) continue;
    } while(0);

    return 0;
}

you get only one iteration, while in this case:

int _tmain(int argc, _TCHAR* argv[])
{
    int i = 0;
    do {
        ++i;
        _tprintf(_T("Iteration %d\n"), i);
        if (i < 30) continue;
        break;
    } while(1);

    return 0;
}

you get 30 iterations. Tested under VS2008.

The do while clauses are logically equivalent. If they are translated to the same byte code depends on the compiler at hand. I guess that most modern compilers will treat them equally.

EDIT based on your comment that you're using a while with breaks in order to be able to break out of the 'loop' when certain conditions have been met.

If this is what you're trying to accomplish:

do
{ 
  // processing step 1
  if( some_condition )
    break;
  // processing step 2
  if( some_condition )
    break;
  // etcetera..
} while(0)

...then just break the code you have in your while loop out to a stand-alone function with multiple returns:

void processing()
{

  // processing step 1
  if( some_condition )
    return;
  // processing step 2
  if( some_condition )
    return;
  // etcetera..
}

int main()
{
  // ...
  processing();
  return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top