Let's start off with some structure:
do
{
// Insert code here.
} while(0);
You should already be familiar with do { /*insert code*/ } while(/*condition*/); but if not, I'll give you a brief explanation. Basically, the code inside the body of the do statement will be executed as long as the condition of the while statement is true.
do
{
x++;
} while (x < 100);
So, this loop will increment x by 1 as long as x is smaller than 100.
do while loops are similar to while loops. The difference between the two is that the condition is evaluated first for a while loop. On the other hand, the condition is evaluated last for the do loop. What this means is that code in the body of a do statement will execute atleast once. Code in the body of a while statement can potentially never execute.
Now that we are familiar with the do while loop, let's get back to talking about do { } while(0);
After the previous explanation of a do while loop, you notice that do {} while(0); looks similar to a piece of code that doesn't have it at all:
do
{
// Insert code here.
} while(0);
Now, at first, this seems pretty useless, why don't we just refactor the code to the following, which is exactly the same:
// Insert code here.
Well there are two reasons that I know of, one dealing with macros, the other dealing with being able to break out of code which is quite common for initializing type of code.
Here is an example without the do while loop:
// Failure will return a null(0) value.
p = CreateNewObject();
if (p != 0)
{
o = CreateDifferentObject();
if (o != 0)
{
//...
}
else
{
//...
}
//...
}
else
{
//...
}
With the do while loop, you can break out of the code on failure:
do
{
// Failure with return a null(0) value.
p = CreateNewObject();
if (p == 0) break;
o = CreateDifferentObject();
if (o == 0) break;
//...
} while(0);
That's all there is to it. I know that it was pretty brief, but I felt like I really had to share this information with the community. Hopefully you found this helpful.







MultiQuote









|