Bjarne Stroustrup (C++ creator) once said that he avoids \"do/while\" loops, and prefers to write the code in terms of a \"while\" loop instead. [See quote below.]
S
This is cleanest alternative to do-while that I have seen. It is the idiom recommended for Python which does not have a do-while loop.
One caveat is that you can not have a continue in the since it would jump the break condition, but none of the examples that show the benefits of the do-while need a continue before the condition.
while (true) {
if (!condition) break;
}
Here it is applied to some of the best examples of the do-while loops above.
while (true); {
printf("enter a number");
scanf("%c", &c);
if (!(c < '0' || c > '9')) break;
}
This next example is a case where the structure is more readable than a do-while since the condition is kept near the top as //get data is usually short yet the //process data portion may be lengthy.
while (true); {
// get data
if (data == null) break;
// process data
// process it some more
// have a lot of cases etc.
// wow, we're almost done.
// oops, just one more thing.
}