'break' statement when using curly braces in switch-case

后端 未结 5 2030
太阳男子
太阳男子 2020-12-30 18:49

I use curly braces with all of my switch case statements in C/Objective-C/C++

I had not, until a few moments ago, considered whether including the break;

5条回答
  •  执笔经年
    2020-12-30 19:31

    There's tons of different coding styles of how to combine curly braces and switches. I'll use the one I prefer in the examples. The break statement breaks out of the innermost loop or switch statement, regardless of location. You could for example have multiple breaks for a single case:

    switch (foo) {
    case 1:
        {
            if (bar)
                break;
            bar = 1;
            ...
        }
        break;
    }
    

    Note that you can also put the cases anywhere, though that is somewhat considered bad practice. The case label is very much like a goto label. It has happened that I've written something like this:

    switch (foo) {
    case 1:
        bar = 1;
        if (0) {
    case 2:
            bar = 2;
        }
        ...
        break;
    }
    

    but use it with care.

提交回复
热议问题