官术网_书友最值得收藏!

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 and each break denotes the end of that case and the point that the execution leaves the switch block.

Optionally, we can also use the default keyword without a value to run some code in case none of the case statements evaluate to true, as follows:

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:

// 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 all we have seen regarding switch is by putting it into action, along with all the other new concepts we are learning about.

Next, we will learn about another C++ concept we need to understand before we write some more code. Let's look at class enumerations.

主站蜘蛛池模板: 汝城县| 体育| 香港 | 朝阳市| 龙海市| 楚雄市| 辽阳市| 五寨县| 南京市| 彝良县| 福海县| 定州市| 桦甸市| 博兴县| 洪雅县| 万盛区| 田东县| 西和县| 林芝县| 通渭县| 新田县| 金山区| 枣阳市| 潍坊市| 延吉市| 邹城市| 临猗县| 广南县| 富阳市| 锡林浩特市| 新巴尔虎左旗| 周至县| 新密市| 东乌珠穆沁旗| 抚宁县| 阿合奇县| 古浪县| 邹平县| 抚松县| 永川市| 堆龙德庆县|