Modern C++: The Good Parts/Let's take a breather.

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Up to now, we've only covered what has been used in our programs, but that's leaving some irritating gaps. This chapter is to fill those gaps.

Loops[edit | edit source]

do..while[edit | edit source]

There's another kind of loop we haven't mentioned:


As you might have guessed, this is very similar to a while loop. A do..while loop reverses the two things done by an ordinary while loop, which are:

  1. check condition, exit if false;
  2. run loop body.

A while loop repeats those two steps over and over until the condition tests false. A do..while loop, in contrast, repeats them like this:

  1. run loop body;
  2. check condition, exit if false.

The effect is that a do..while loop guarantees one iteration, whereas a while loop might not run its body at all. This is useful, in particular, when you're reading data from somewhere else, like a file, and whether you should continue depends on what you've read.

break[edit | edit source]

Loops can be a whole lot more complicated than "start..repeat until X..exit". That complexity can be a very bad thing, but it can also be very useful.

For example, completing a loop is not the only way out. Remember the break statements used in switches? Well, they can also exit loops. If you have a loop in a loop in a loop (another example of nasty complexity), break will only exit the smallest one it's in. If you have a switch in a loop, break inside the switch will only exit the switch.

If you like, imagine that the language starts from the break statement, searches backward through the code, and exits the first loop or switch it finds.

Here's an example of break in a loop:

#include <iostream>
#include <string>

int main()
	std::string input;
	int count;

	std::cout << "Welcome to the lister! How many items would you like to list? > ";
	std::cin >> input;
	count = std::stoi(input);

	std::cout << "If you change your mind, enter STOP after the last item.\n\n";
	for(int i = 0; i < count; i++)
		std::cout << (i + 1) << ". ";
		std::cin >> input;
		if(input == "STOP")

continue[edit | edit source]

Switches[edit | edit source]

Functions[edit | edit source]