Search

7.8 — Do while statements

Consider the case where we want to show the user a menu and ask them to make a selection -- and if the user chooses an invalid selection, to ask them again. Clearly the menu and selection should go inside a loop of some kind (so we can keep asking the user until they enter valid input), but what kind of loop should we choose?

Since a while loop evaluates the condition up front, it’s an awkward choice. We could solve the issue like this:

But this only works because our initial value of 0 for selection isn’t in the set of valid values (1, 2, 3 or 4). What if 0 was a valid choice? We’d have to pick a different initializer to represent “invalid” -- and now we’re introducing magic numbers (4.13 -- Literals) into our code.

We could instead add a new variable to track validity, like so:

While this avoids the magic number, it introduces a new variable just to ensure the loop runs once, and that adds complexity and the possibility of additional errors.

Do while statements

To help solve problems like the above, C++ offers the do-while statement:

do
    statement
while (condition);

A do while statement is a looping construct that works just like a while loop, except the statement always executes at least once. After the statement has been executed, the do-while loop checks the condition. If the condition evaluates to true, the path of execution jumps back to the top of the do-while loop and executes it again.

Here is our example above using a do-while loop instead of a while loop:

In this way, we’ve avoided both magic numbers and additional variables.

One things worth discussing in the above example is that the selection variable must be declared outside of the do block. If the selection variable were to be declared inside the do block, it would be destroyed when the do block terminates, which happens before the conditional is evaluated. But we need the variable in the while conditional -- consequently, the selection variable must be declared outside the do block (even if it wasn’t used later in the body of the function).

In practice, do-while loops aren’t commonly used. Having the condition at the bottom of the loop obscures the loop condition, which can lead to errors. Many developers recommend avoiding do-while loops altogether as a result. We’ll take a softer stance and advocate for preferring while loops over do-while when given an equal choice.

Best practice

Favor while loops over do-while when given an equal choice.


7.9 -- For statements
Index
7.7 -- Intro to loops and while statements

34 comments to 7.8 — Do while statements

  • Kevin

    I decided to take the code here and what I've learnt so far to make a calculator that takes two values, asks what operation, and throws up errors if an invalid character is entered. I have it functioning exactly how I want it... but I'm curious if I've made newbie mistakes, and if there are easier ways to do it.

  • R00kie

    Hi Alex,

    I was playing with a piece of code that I wrote testing the Do/While loops, a calculator pretty similar with the the ones in the comments above and I came across this problem :

    My calculator works pretty well, except when I try to enter an invalid number…it goes ballistic afterwards.

    How can I put a condition that checks the data type for my X and Y and if it’s not double/integer etc to simply cout a message like " you’ve entered an invalid character, not an integer/double etc " .

    What condition should I write for my "switch" or "if" to check if my data type is an integer/double , or "else" to show me and error message ???

    or better yet to show me the " Enter number " message again ???

    • Alex

      You can use the following code to detect a failed input and remove the invalid characters from the I/O stream:

  • zee

    hi friends i am new comer in c++ i am so confused about do while loop some1 plz help me

  • EXPLOSIVEXPLOSION

    Shouldn't the and's (&&) in the above example be or's (||)?

    • codeez

      If we used Logical OR, we'd get 'short circuit evaluation' if the first || was true so we'd never even check to see if the next number was correct.

      --
      Still learning, so correct me anyone if I'm wrong :)

  • Bao Nguyen

    The sign does not show up :

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">