The switch statement in the C++

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 choice switch 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 value answer, which introduces the user. Then look, how interesting works switch() : in parentheses pass him answer (string 16) and next to each word case write possible values answer, 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 value case coincides with the value of answer. Statement break 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. If answer equal to 1, work case 1 and the screen will show the, that it is registered to a keyword break, and all other case, They will be ignored. If answer equal to 2 – executed only case 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 block default. Before him it comes, just then, when none of case not worked and, respectively, not fulfilled none break 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 value answer, 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:

What you should remember:

syntax:

block default It can be positioned anywhere in the block switch() 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(), whether default 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()

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

Post navigation

40 thoughts on “The switch statement in the C++”

Comment navigation

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.

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.

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.

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.

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!

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.

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;

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…

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.

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.

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.

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!

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).

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!