binary01
binary01

Reputation: 1898

standalone break within a switch statement

I stumbled upon this code, which works as expected:

switch (ev->deviceType) {

    break;

    case DEVICE_TS1E0:
        //some code
        break;

    case DEVICE_TS1E3:
       //some code
       break;

    default:
        //some logging
        break;
}

Now, there's a lonesome break; at the start of the switch, which appears to have no effect.

Is there any circumstances where that break; would have an effect ?

Upvotes: 4

Views: 74

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134356

TL;DR That break statement is ineffective and a dead-code. Control will never reach there.

C11 standard has a pretty good example of a similar case, let me quote that straight.

From Chapter §6.8.4.2/7, (emphasis mine)

EXAMPLE In the artificial program fragment

switch (expr)
{
    int i = 4;
    f(i);
case 0:
    i = 17;
    /* falls through into default code */
default:
    printf("%d\n", i);
}

the object whose identifier is i exists with automatic storage duration (within the block) but is never initialized, and thus if the controlling expression has a nonzero value, the call to the printf function will access an indeterminate value. Similarly, the call to the function f cannot be reached.

Upvotes: 4

fluter
fluter

Reputation: 13816

That statement, along any other statements that is not in a case clause in switch statement are unreachable code, aka dead code. That means they will not be run anyway. It is not recommended to use them.

Upvotes: 2

Related Questions