Making decisions with switch
We have already looked at if
, which allows us to decide whether to execute a block of code based upon the result of its expression. But sometimes, a decision in C++ can be made in other ways that are better.
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 can start a switch
decision as follows:
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:
case x: //code for x break; case y: //code for y break;
As you can see, each case
states a possible result...