Making decisions with switch
We have already seen the if
keyword, which allows us to decide whether to execute a block of code based on the result of its expression, but sometimes, a decision in C++ can be better made in other ways. It is often used for providing an elegant alternative to a series of nested if-else
statements. As we will see, it evaluates an expression and directs program flow.
When we must make a decision based on a clear list of possible outcomes that don’t involve complex combinations or wide ranges of values, then switch
is usually the way to go. We start a switch
decision like this:
switch(expression)
{
// More code here
}
In the previous example, expression
could be an actual expression or just a variable. Then, within the curly braces, we can make decisions based on the result of the expression or value of the variable. We do this with the case
and break
keywords, as in this slightly abstract example:
case x:
//code for x
break...