Making decisions with switch

We have already seen if, which allows us to make a decision whether to execute a block of code based upon the result of its expression. Sometimes a decision in C++ can be better made in other ways.

When we have to make a decision based on a clear list of possible outcomes, which doesn't involve complex combinations or wide ranges of values, then switch is usually the way to go. We start a switch decision as we can see in the following code:

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 the value of the variable. We do this with the case and break keywords:

case x: 
    //code to for x 
    break; 
  
case y: 
    //code for y 
    break; 

You can see in the previous abstract example that, each case states a possible result and each break denotes the end of that case and the point at which execution leaves the switch block.

We can also, optionally, use the default keyword without a value, to run some code in case none of the case statements evaluate to true. Here is an example:

default: // Look no value 
    // Do something here if no other case statements are true 
    break; 

As a final and less abstract example for switch, consider a retro text adventure where the player enters a letter such as 'n', 'e', 's', or 'w' to move North, East, South, or West. A switch block could be used to handle each possible input from the player, as we can see in this example:

// get input from user in a char called command 
 
switch(command){ 
 
   case 'n': 
      // Handle move here 
      break; 
 
   case 'e': 
      // Handle move here 
      break; 
 
   case 's': 
      // Handle move here 
      break; 
 
   case 'w': 
      // Handle move here 
      break;    
    
   // more possible cases 
 
   default: 
      // Ask the player to try again 
      break; 
 
} 

The best way of understanding everything we have learned about switch will be when we put it into action along with all the other new concepts we are learning.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.66.185