Search code examples
cdo-while

Significance of do{} while(0)


What is the significance of do while loop when the condition inside the while loop is 0 i.e. always false.

do
{

//some code implementation.

}while(0);

I have seen at many places this is being used. What is its importance, Cant we just omit the do while(0). as both ways code will be executed only once.

It is not a duplicate as i asked about use of while(0) condition specifically not general do-while loop.


Solution

  • It can be used to leave a certain scope of code at any point without leaving the function. Consider:

    do
    {
      beginAtomicOperationSequence();
    
      ret = doSomething();
      if (ret < 0) break;
    
      ret = doSomething2();
      if (ret < 0) break;
    
    } while(0);
    
    if (ret < 0) {
      switch (ret) {
       //handle error
      }
      rollbackAboveOperations();
    } else {
      commitAboveOperations();
    }
    

    There are some cases in which I would say that this is acceptable, particularly if one needs to make a sequence of operations which are to be considered atomic. Like in the example above.