Here’s a useful tip for beginning programmers.
We’ve all used Switch statements lots of times. As a student, you learn that you need to include a break statement after the body of each case to avoid the spill-over effect. I’ve always chalked this up to language design, and never saw value in the “spill-over”… until recently!
For example: A simple use of a switch statement.
int num; cin >> num; switch(num){ case 1: cout << "You put in 1\n"; break; case 2: cout << "You put in 2\n"; break; }
The idea is that if you didn’t put the break in the body of case option 1, after printing “You put in 1\n”, the body of case option 2 would be executed.
There is value in the “spill-over”! Let’s say that you wanted both options 1 and 2 to trigger the printing of some text. You can use the lack of a break statement to achieve this!
int num; cin >> num; switch(num){ case 1: case 2: cout << "You put in either 1 or 2\n"; break; }
If the user enters 1, then the body of case option 1 gets executed (of course, it’s empty right now). The important thing to note is the lack of a break statement in the body of case option 1! The behavior of the system now dictates that after executing the trivial body of option 1, we spill over into the body of case option 2!
At the end of the day, this behavior means that you can enter either of the two inputs (numbers 1 or 2) to trigger some case!
A more useful example
Let’s say that I want to allow the user to quit your system either by pressing the ‘q’ key, or an uppercase version ‘Q’. A switch statement can now be used effectively!
Instead of:
switch(menuChoice){ case 'q': exit(0); break; case 'Q': exit(0); break; }
We can simplify this to become:
switch(menuChoice){ case 'q': case 'Q': exit(0); break; }
Which, again, means that you can input either a ‘q’ or a ‘Q’ to exit the system!