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 the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.