0

I just solved 1st exercise on learncpp, chaper 7.8. I tested their version of switch loop and it works, but I wonder it's without break, shouldn't in this case such code cause undesired behavior? When can I leave out break?

Here is my version(which also works correctly):

switch (op)
    {
    case '+': {
        return add;
            break;}
    case '-': {
        return subtract;
        break;}
    case '*': {
        return multiply;
        break;}
    case '/': {
        return divide;
        break;}
    default: ;
    }
econ
  • 495
  • 3
  • 6
  • 16
  • 12
    1st of all `switch` isn't a loop. And there's no need to have a `break;` statement after the `return`statements. – user0042 Sep 13 '17 at 16:22
  • 1
    It depends if you want fall through or not. If you don't you need `break`. If not then you don't. – NathanOliver Sep 13 '17 at 16:23
  • 4
    Read about what `break` and `return` do and the answer will become clear. Don't rely on testing to learn C++. – nwp Sep 13 '17 at 16:24
  • 5
    Also, I would recommend learning C++ from a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) instead of internet tutorials. – NathanOliver Sep 13 '17 at 16:25
  • The word "switch" doesn't exist on the page you link to. Thus, there's no way to answer. Further, questions *must* be self contained. All information necessary to know what the question is must be *in the question*. Thus, asking us to go look at code on some other site is off-topic. – Makyen Sep 14 '17 at 05:48

5 Answers5

9

Without break, the flow of execution will simply continue to the next case - unless you jump in some other way of course (like returning, in your case). This is known as fall-through.

Whether this is a bug or not depends on the program. It can be useful if (for example) you want multiple cases to have the same action:

switch (op)
{
    case '+':
        return add;
        break;  // these breaks do nothing - we have already returned!
    case '-':
        return subtract;
        break;
    case 'x':  // fall through to '*'
    case '*':
        return multiply;
        break;
    case '/':
        return divide;
        break;
}
Phydeaux
  • 2,795
  • 3
  • 17
  • 35
  • A great example of Fall-through in action is [Duff's Device](https://stackoverflow.com/questions/514118/how-does-duffs-device-work) – user4581301 Sep 13 '17 at 17:38
5

Note that C++ does not insist on your using break, but often switch cases depend on them, to obviate the useful follow through feature.

You can remove a break with no effect on your program if program control never reaches it: None of the break statements after the return statements are reachable, so you can safely remove them.

You also don't need an empty default label either.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
4

Since you are new to C++, consider that:

  • Anytime your code reaches a return statement, your current function/method will end and return the specified valued without executing any more line of codes. So your break statements are never going to be reached.

  • When a break is reached, the current switch, while or for will end. And the flow will continue outside of its scope {...}.

  • If you do not use break in a switch case then the flow just continues (even to the next case).

3

It may be useful to you to understand what a switch is doing under the covers.

essentially this:

enum command {
    add, subtract, multiply, divide, error
};

command foo(char op)
{
    switch (op)
    {
    case '+': {
        return add;
            break;}
    case '-': {
        return subtract;
        break;}
    case '*': {
        return multiply;
        break;}
    case '/': {
        return divide;
        break;}
    default: 
      break;
    }
    return error;
}

Is logically the same as this:

command foo_that_will_give_people_seizures(char op)
{
    if (op == '+') goto plus_;
    if (op == '-') goto minus_;
    if (op == '*') goto mpy_;
    if (op == '/') goto div_;
    goto break_;

    plus_:
    return add;
    goto break_;   // notice how this statement cannot be reached.

    minus_:
    return subtract;

    mpy_:
    return multiply;

    div_:
    return divide;

    break_:
        ;
    return error;
}

and the statement break; appearing in any of the cases in the first function is equivalent to goto break_ in the second.

ps. you won't win any friends writing code like this. People like to pretend that goto is a bad thing in c++ ;-)

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
1

You should be aware that break should be left out on default: (if the default is the last case) where the code flow basically reaches the end and doesn't need to get break.

The very purpose of break is to prevent code to continue to next case(s) when the actual case is true. return however, returns the given statement in the case and breaks the switch. If you are considering to return inside switch cases, then instead of using break, you may use return foobar; It will break by returning whatever you wish to return.

knoxgon
  • 1,070
  • 2
  • 15
  • 31