Equivalent using for-loop instead do-while-loop

10,183

Solution 1

Any sort of a loop can be constructed from a combination of an infinite "forever" loop, and a conditional break statement.

For example, to convert

do {
    <action>
} while (<condition>);

to a for loop, you can do this:

for (;;) {
    <action>
    if (!<condition>) break;
}

You can use the same trick to convert a do/while loop to a while loop, like this:

while (true) {
    <action>
    if (!<condition>) break;
}

Moreover, the loop is not needed at all: any of the above can be modeled with a label at the top and a goto at the bottom; that is a common way of doing loops in assembly languages. The only reason the three looping constructs were introduced into the language in the first place was to make the language more expressive: the do/while loop conducts author's idea much better than any of the alternatives shown above.

Solution 2

There is no other loop that executes the loop content at least once, as do-while does. Of course you could emulate do-while with a flag and a while loop:

do {
    A;
} while (B)

becomes

int flag=1;
while (flag || B) {
    flag=0;
    A;
}

but that's not really an alternative, it just obscures your original intent.

Solution 3

The following three loops are all equivalent:

#define FALSE (0)
#define TRUE  (!(FALSE))

do
{
    status = getStatus();
}
while(status == TRUE);

status = TRUE;
while(status == TRUE)
{
    status = getStatus();
}

for(status = TRUE; status == TRUE; status = getStatus())
{
}
Share:
10,183
deathshot
Author by

deathshot

Updated on August 05, 2022

Comments

  • deathshot
    deathshot almost 2 years

    I was wondering instead of using a do-while loop, what is the equivalent for-loop or any other combination of loops in c?