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 ...

Get C++ Primer Plus now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.