I was wondering instead of using a do-while loop, what is the equivalent for-loop or any other combination of loops in c?
3 Answers
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.

- 714,442
- 84
- 1,110
- 1,523
-
-
@deathshot Yes, a "breaking" condition is the negated "continuation" condition. – Sergey Kalinichenko Dec 23 '13 at 00:03
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.

- 9,667
- 2
- 24
- 31
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())
{
}

- 8,712
- 3
- 28
- 46
-
Oh, I was really hinting that that would idiomatically be written as `status`, not `status == true`. – Oliver Charlesworth Dec 23 '13 at 14:13
-
Just trying to be explicit for the sake of new programmers. It definately looks better use `while(status)`. – Fiddling Bits Dec 23 '13 at 14:44
-
And shouldn't that be `status = TRUE;` as well (rather than `true`) for the assignment before the while? – Rich May 07 '15 at 13:52