Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ logic with switch statements

I'm starting to grasp c++ but there is one thing that confuses me and it's using break and select case. I know how to do this but what I would like to understand is why this certain operation happens.

Say if i have

switch (Tasty)
{
  case true:
    cout << "yum" << endl;
    break;
  case false:
    cout << "erch" << endl;
  break;
}

Now that does it correctly and prints out what I want, but if I do

switch (Tasty)
{
  case true:
    cout << "yum" << endl;
  case false:
    cout << "erch" << endl;
}

Why does it print both "yum" and "erch"?

like image 722
user2437820 Avatar asked Sep 11 '26 19:09

user2437820


2 Answers

The cases in a switch statement are best thought of as labels. After the statement

cout << "yum" << endl;

finishes running, the next one simply starts running,

cout << "erch" << endl;

unless you explicitly break out of the switch statement.

like image 146
Brian Bi Avatar answered Sep 14 '26 08:09

Brian Bi


The answers here are good, I just want to give you an example where omitting break is actually useful:

In a case you can't check for multiple values, like 1 || 2 || 3, so if you want to perform the same function for more than one value your option would be to repeat code, something like this:

switch (a)
{
  case 1:
    Foo();
    break;

  case 2:
    Foo();
    break;

  case 3:
    Foo();
    break;

  case 4:
    Bar();
    break;
}

unless you omit the break and you can write:

switch (a)
{
  case 1:
  case 2:
  case 3:
    Foo();
    break;

  case 4:
    Bar();
    break;
}

Code repetition is something to always be avoided if possible so this actually comes in handy.

like image 27
bolov Avatar answered Sep 14 '26 08:09

bolov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!