switch
and if else
Both the switch
statement and the if else
statement let a program select from a list of alternatives. The if else
is the more versatile of the two. For example, it can handle ranges, as in the following:
if (age > 17 && age < 35)
index = 0;
else if (age >= 35 && age < 50)
index = 1;
else if (age >= 50 && age < 65)
index = 2;
else
index = 3;
The switch
statement, on the other hand, isn’t designed to handle ranges. Each switch
case label must be a single value. Also that value must be an integer (which includes char
), so a switch
statement can’t handle floating-point tests. And the case label value must be a constant. If your alternatives involve ranges or floating-point tests or comparing two variables, you should use if else
.
If, however, all the alternatives can be identified with integer constants, you can use a switch
or an if else
statement. Because that’s precisely the situation that the switch
statement is designed to process, the switch
statement is usually the more efficient choice in terms of code size and execution speed, unless there are only a couple alternatives from which to choose.
If you can use either an if else if
sequence or a switch
statement, the usual practice is to use switch
if you have three or more alternatives.
break
and continue
StatementsThe break
and continue
statements enable a program to skip over parts of the code. You can use the break
statement in a switch
statement and in any of the loops. It causes program execution to pass to the next statement following the switch
or the loop. The continue
statement is used in loops and causes a program to skip the rest of the body of the loop and then start a new loop cycle (see Figure 6.4).
Listing 6.12 shows how the two statements work. The program lets you enter a line of text. The loop echoes each character and uses break
to terminate the loop if the character is a period. This shows how you can use break
to terminate a loop from within when some condition becomes true
. Next the program counts spaces but not other characters. The loop uses continue
to skip over the counting part of the loop when the character isn’t a space.
// jump.cpp -- using continue and break
#include <iostream>
const int ArSize = 80;
int main()
{
using namespace std;
char line[ArSize];
int spaces = 0;
cout << "Enter a line of text:
";
cin.get(line, ArSize);
cout << "Complete line:
" << line << endl;
cout << "Line through first period:
";
for (int i = 0; line[i] != ' '; i++)
{
cout << line[i]; // display character
if (line[i] == '.') // quit if it's a period
break;
if (line[i] != ' ') // skip rest of loop
continue;
spaces++;
}
cout << "
" << spaces << " spaces
";
cout << "Done.
";
return 0;
}
Here’s a sample run of the program in Listing 6.12:
Enter a line of text:
Let's do lunch today. You can pay!
Complete line:
Let's do lunch today. You can pay!
Line through first period:
Let's do lunch today.
3 spaces
Done.
3.149.27.72