The basics of programming in c++ for beginners

The switch statement in the C++

оператор switch, switch c++, switch в с++, оператор множественного выбора, свич с++, основы программированияIn this article, we slightly modify the format of the study topics. At the beginning, let's look at an example with statement switch(switch), which will be a lot of comments about how, that occurs in the code. A whole theory will be located below.

The work of the statement of multiple choiceswitch in C ++, we consider in addressing this problem: Let's, the user has a numbered list of the metro stations in Barcelona. You must write code, wherein the dialogue with the user is implemented, namely, asked to enter room underground station. After entering the Station Number, we have to show it on the screen and the name of the travel time. If, however, with the number of stations is not, inform and propose to enter the number again. Begin:

To string 13 – everything is clear: Ads necessary variables, conclusions Questions on the screen, and entry into the loop do while. In string 14 we got valueanswer, which introduces the user. Then look, how interesting works switch() : in parentheses pass him answer (string 16) and next to each wordcase  write possible valuesanswer, the user can enter (1, 2, 3 …).

after each case you see the statement : , he required. It is followed by the command, that must be met, if the valuecase coincides with the value of answer. Statementbreak  at the end of each block case  It is also required. It indicates to the compiler, if this case It was performed, you have to get out of switch().  That is actually, when performed switch () begins search and search for the desired case.

Ifanswer  equal to 1, work case 1 and the screen will show the, that it is registered to a keywordbreak, and all other case, будут проигнорированы. Если answer equal to 2 – executed onlycase 2 and exited switch(). What if no value blocks case does not match, with the value, that took switch() (in our case answer)? For this purpose the blockdefault. Before him it comes, just then, when none of case not worked and, respectively, not fulfilled nonebreak  these units.

In our example,, it will work if the value, which will bring the user, will be <1 or >5. Then the user will see on the screen a message that, that with such a number of subway stations, and there is no need to re-enter.

In the loop, we always check the valueanswer, which is entered by the user. This is done using if . If the value is within a suitable range, we (from 1 to 5 ), the manipulated variable var It will be set 0. In this case, the user will no longer be prompted to enter a new value.

Here's how the program works:

оператор switch, switch c++, switch в с++, оператор множественного выбора, свич с++

 What you should remember:

  • syntax:

оператор switch, switch c++, switch в с++, оператор множественного выбора, свич с++

    • blockdefault  It can be positioned anywhere in the blockswitch()  For example the first and second case . His code in any event will run only, if you find the value in the blocks case. But, I suggest you have it at the end, as do most programmers. It is an unwritten rule.
    • a lower block switch(), whetherdefault or case, operator break  You can not specify. This is done in this example. But we should remember, that in all other break mandatory!
    • default  It is optional. His in switch()  may not be at all. In this case, If no value blocks case  does not coincide with the, that took switch() , the program moves to the next line of code, located under the switch()
  • sometimes blocks case  check character, instead of numerical values. Then you must take these characters in single quotes –  case ‘b’: ,  case ‘G’: ,  case ‘+’ etc.

Anyone who has a desire to – see video tutorial on the topic.

Still have questions – ask them in the comments. Be sure to answer all.   Learn the basics of programming with us! More examples usingswitch  in C ++ discussed in the article Tasks:  The switch statement in the C++.

49 thoughts on “The switch statement in the C++

  1. Not working my program, although I do everything for your article. Probably in a switch can not declare variables. Why, and whether it is a standard fixed?

    1. Vladimir, but our program does not declare variables in the body switch. They are declared at the beginning of the main function and input data from the keyboard is to switch
      And you can create a variable, But the question, why it is needed, if its scope ends at the exit of the switch body. And another important point – it will only create a lowermost unit case or default (because it can not violate the syntax) and only, if it is (the lower block) It will not contain break.

      1. still I do not see any reason to declare variables to fakie, I tried, before the default operating, but I do not see sense… I can not understand the technical application, and therefore I think the idea worthless! variable still needs to be declared to the switch operator!

      1. Yes, even if skopipastit code and enter # station '111111111’ or any other value, greater than int - the program will endlessly display preset number … no!
        Сделайте правильный выбор (from 1 to 5)

  2. And even after you login through VC avatar of all users are displayed, like mine. I hope this is only because I see)

  3. Get rid of like this:

    do{
    cin >> answer; // ввод значения
    cin.clear();

    ... Тут остальной код

    } while (var); //цикл повторится, пока var не изменит значение на false
    system("pause");

    The trick, you need to clear the input buffer, if we are permitted overflow.

    1. with the numbers it works, and how to deal with letters or symbols? in order to eliminate accidental button. but it also brings an infinitely station at number … no etc.

      1. Replacements
        cin >> answer; // ввод значения
        On
        do
        {
        cout < < "Введите номер станции метро, для расчета времени в пути (от 1 до 5): "; cin.clear(); cin.sync(); cin >> answer;
        } while (cin.fail());

    1. Break statement in the alternative, (branch) switch is used almost always. In C / C ++ language switch statement “passage”: After working out the desired alternative, without a break Released, begins to be practiced next, then the next, etc..

      In some languages, (Go, for example) the switch statement “does not pass”, and there is a way out of alternatives (branch switch) there is no break.

      And to the question “since when?” answer is simple: “always“.

      1. The answer is simple – never break was not required in any C, our C ++.
        About “almost always”… let us say, I need to treat y / n keyboard. I will write:
        case “Y”:
        case “Y”:
        case “D”:
        case “д”:
        yes();
        break;
        And the same goes for the No. Such use is standard and quite often.

    1. Goto statement should be avoided, except in very rare cases … the initial stages, in the coming years, these cases you will not imagine ever. Using goto is considered bad style.

      The alternative is the standard default alternative to the switch statement, its use is considered good practice.

  4. > Fedor Odintsov

    Without a break all the branches of the switch will be executed one after the other, until the last default. This is obviously not the, what is written switch. Therefore, almost always each branch switch must end with a break.
    In those rare cases, when it is expected to perform several consecutive branches, break can not be used.

    1. The article is written for beginners:
      ” break statement at the end of each block in the same case is optional.” and “But we should remember, that in all the rest break is required!”. About any “almost always” there is no question. At the beginner seems, that the break is always needed, not just in this case,. Where the article is written, the, what you write in your comments?

Leave a Reply

Your email address will not be published. Required fields are marked *