[c#] 'do...while' vs. 'while'

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 and
  • there is a potential infinite loop while (c!='\n') c=getc(stream);

Conclusion: avoid do / while loops and look for bugs when you see one.

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to c

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf?

Examples related to while-loop

While, Do While, For loops in Assembly Language (emu8086) MySQL Insert with While Loop Python loop to run for certain amount of seconds How to break a while loop from an if condition inside the while loop? How to find sum of several integers input by user using do/while, While statement or For statement Python: How to keep repeating a program until a specific input is obtained? Creating multiple objects with different names in a loop to store in an array list ORA-06502: PL/SQL: numeric or value error: character string buffer too small How to break out of a loop in Bash? for or while loop to do something n times

Examples related to do-while

How to find sum of several integers input by user using do/while, While statement or For statement WHILE LOOP with IF STATEMENT MYSQL Emulating a do-while loop in Bash JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100 Are "while(true)" loops so bad? Do while loop in SQL Server 2008 do-while loop in R 'do...while' vs. 'while' How to emulate a do-while loop in Python?