This is my personal opinion, but this question begs for an answer rooted in experience:
I have been programming in C for 38 years, and I never use do
/ while
loops in regular code.
The only compelling use for this construct is in macros where it can wrap multiple statements into a single statement via a do { multiple statements } while (0)
I have seen countless examples of do
/ while
loops with bogus error detection or redundant function calls.
My explanation for this observation is programmers tend to model problems incorrectly when they think in terms of do
/ while
loops. They either miss an important ending condition or they miss the possible failure of the initial condition which they move to the end.
For these reasons, I have come to believe that where there is a do
/ while
loop, there is a bug, and I regularly challenge newbie programmers to show me a do
/ while
loop where I cannot spot a bug nearby.
This type of loop can be easily avoided: use a for (;;) { ... }
and add the necessary termination tests where they are appropriate. It is quite common that there need be more than one such test.
Here is a classic example:
/* skip the line */
do {
c = getc(fp);
} while (c != '\n');
This will fail if the file does not end with a newline. A trivial example of such a file is the empty file.
A better version is this:
int c; // another classic bug is to define c as char.
while ((c = getc(fp)) != EOF && c != '\n')
continue;
Alternately, this version also hides the c
variable:
for (;;) {
int c = getc(fp);
if (c == EOF || c == '\n')
break;
}
Try searching for while (c != '\n');
in any search engine, and you will find bugs such as this one (retrieved June 24, 2017):
In ftp://ftp.dante.de/tex-archive/biblio/tib/src/streams.c , function getword(stream,p,ignore)
, has a do
/ while
and sure enough at least 2 bugs:
c
is defined as a char
andwhile (c!='\n') c=getc(stream);
Conclusion: avoid do
/ while
loops and look for bugs when you see one.