Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Falling through switch statement (works sometimes?)

I have a switch statement such as the one below:

switch (condition)
{
    case 0:
    case 1:
        // Do Something
        break;
    case 2:
        // Do Something
    case 3:
        // Do Something
        break;
}

I get a compile error telling me that Control cannot fall through from one case label ('case 2:') to another

Well... Yes you can. Because you are doing it from case 0: through to case 1:.

And in fact if I remove my case 2: and it's associated task, the code compiles and will fall through from case 0: into case1:.

So what is happening here and how can I get my case statements to fall through AND execute some intermediate code?

like image 475
Michael Mankus Avatar asked Feb 17 '26 13:02

Michael Mankus


1 Answers

There is a difference between stacking labels and fall-through.

C# supports the former:

case 0:
case 1:
    break;

but not fall-through:

case 2:
    // Do Something
case 3:
    // Do Something
    break;

If you want fall-through, you need to be explicit:

case 2:
    // Do Something
    goto case 3;
case 3:
    // Do Something
    break;

The reasoning is apparent, implicit fall-through can lead to unclean code, especially if you have more than one or two lines, and it isn't clear how the control flows anymore. By forcing the explicit fall-through, you can easily follow the flow.

Reference: msdn

like image 152
Femaref Avatar answered Feb 19 '26 01:02

Femaref



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!