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. Fyodor, I did not write this article … and not even read properly. But it said that, that the break in the trees of choice practically almost always necessary, the initial stages of the study is very helpful.

    They, Fyodor, who wrote many thousands of industrial code by profession (like me), in distinction from degeneratov, who write only comments in the forums (like you) know, that skipping break in a switch where it is needed – the most difficult cause of errors, which are only many hours of debugging.

    1. 1. "Chukchi not the reader - Chukchi writer!»
      2. “and not even read properly”
      I have nothing to add to my previous post.

    2. That is all, who by profession is not super steep cheater with mathematical megaintellektom and experience in developing a code of rolls – degenerate?
      Then you – sidedly developed bot with the claim.

      How noviček, I personally understand, I'm not in Cambridge or okforde, what would I have been taught “ideally” and very grateful to Fedor for his work!

  2. Why is my code not repeated when you enter an incorrect value?

    1. How should repeat the code? I'm in this listing cursory glance found 6 errors, due to which it will not compile. Can, his first run at least, and only then look for errors?

      1. Nekorekktno code appears in some places. And the error of my version of the compiler errors no. But while not deyvstvuet for some reason. I asked to help me understand some of. And do not write empty comments.

    2. #include

      using namespace std;

      int main()
      {
      setlocale(LC_ALL, “rus”);
      int firstNumber = 0;
      int secondNumber = 0;
      int composition = firstNumber * secondNumber;
      bool a = true;
      do {
      cout << "Введите первый множитель: " <> firstNumber;
      cout << "Введите второй множитель: " <> secondNumber;
      cout << "Введите решение: " <> composition;
      if (composition == firstNumber * secondNumber)
      {
      cout << "Верно!" << endl;
      a = false;
      }
      else
      {
      cout << "Неправильный ответ. Try again." << endl;
      }
      } while (a); //cycle will be run until a == true
      system("pause");
      return 0;
      In order:
      1. variables firstNumber, secondNumber and composition you outlined, but where the input variables of the user?
      2. Second: The cycle is called do while. You only while present.
      Чтобы было понятнее do переводится как "делать что-то", а while как "в то время как".
      Above the correct code using the do while loop.

    1. What you attentive… So heed the)
      All your life you are looking for errors. You are asked to help, and you are looking for errors? If you are so arrogant, then check error, you are in my code found. Although the entire code – error, site map it is not so, him in my IDE written.

      1. Where did you get the information, I'm a lifetime looking for errors? We have devised?
        We are asked to help find a mistake (because if something does not work or does not work, An error code?), but the errors we should not seek? And yes, if the code will not compile, the logical errors in it to look foolish.
        Based on your words, I believe, that to prove the fact, I'm not arrogant, I need not specify just bugs me. Good, I will not.

  3. No, did not invent. Most Commented seen. the code is compiled. Just ignore the command while the program, that's all. Based on your words, You can not help me with my problem, and therefore, write comments off topic. You can not – do not!

    1. That code, that you were able to bring, not compile, and other code we can not see, You do not show. but you, yet, want to, we have learned to telepathically, what kind of code is stored on your computer and solve the problem.
      I guess, that while not working, because the value of the condition (var == true) != true, but the variable var is not defined and is not assigned anywhere, and why it is needed, known only to you. But this is only assumption, tk. in the condition can contain all, anything, You do not know, that there pastebin-services, not at korežaŝie.

      1. I carried far away from all of the code while. No, is not the fault of var, because on my computer (funny you noticed), no var… Even if var instead put some trueOrFalse, as I have in my IDE, the code does not work.
        I'll try to write code without tags
        #include
        using namespace std;

        int main()
        {
        setlocale(LC_ALL, “rus”);
        int firstNumber = 0;
        int secondNumber = 0;
        int composition = 0;
        cout <> firstNumber;
        cout <> secondNumber;
        cout <> composition;

        if (composition == firstNumber * secondNumber)
        {
        cout << "Правильный ответ. Are you over the summer is not all forgotten!";
        }
        else
        cout << "Неправильный ответ. Now you know, things to do… Попробуйте еще раз! By the way, correct answer – " << firstNumber * secondNumber << endl;
        }
        }

  4. good afternoon!
    Thank you very much for the article, but still I feel compelled to note a caveat, certainly I do not want to generalize, but anyway: Russian-speaking people often citing the example program, does not lead to its content Russian – I have a normal question: that prevents, eg lead Moscow metro station, or railway station Irkutsk region, and, of course, in Russian?
    “Hello world!”.
    My question does not require an answer, and can be seen, only, as thought, which has a right to exist.
    Citizen of the world…

    1. Because it is a classic. The first program in C language was “Hello world!”.
      Another reason – the first program started in console, and there is usually no Russian language without any additional settings.
      Well, and there is no programmer English.

      1. Yes, accustomed to seeing the first program is that about which you write. Problems with Russian encoding resolved almost all, who is himself a native speaker and, respectively, It uses a PC, whether linux, or Windows. Your opinion on this matter is clear. thanks for the answer.

    2. Besides, that have already been answered: presentation of the Russian-speaking (Chinese-or) rows in C / C ++ is dependent on the operating system (Windows, Linux e t.d.), encoding used by (CP-866, CP-1251, UTF-8, UTF-16 and TD). Therefore, the work with the Russian lines in the C / C ++ is much more difficult, than Latin characters, and requires adequate professional.

      P.S. Therefore, at the initial stage of development is not a game and play it safe with the Russian lines.

      1. Perhaps, of course, it is so indeed. But nonetheless, I never faced these problems, anyway – the scale of problems, yet, in my opinion, exaggerated. Your motivation is clear to me. thanks for the answer!

      2. Not “perhaps”, that is the way it is: for correct with localized texts (Russian, Chinese, Arabic) you obliged to instead use a char type “broad” characters UNICODE wchar_t, and instead of string – wstring, respectively… And others (similar) function string works, eg wcslen() instead strlen() (all the same, но wcs*() вмесчо str*()). And that's another technique.
        And only in cases, when your operations are concerned indiscriminately Internal line content, you can use the function strcp(), strcat() etc., while at the same time you're making incorrect actions get the correct result! But it is good to keep in mind and understand what happens (вот strlen() for Russian lines you will always give the wrong result).

  5. online compiler when typesetting numbers do not fulfill the conditions – error occurs – It begins scribbling endless loop “enter the station from …. to… “, “station under number … no” and so on and so forth…
    Probably something in the code is not quite right!

Leave a Reply

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