Valid, but worthless syntax in switch-case?

2020-05-11 10:50发布

Through a little typo, I accidentally found this construct:

int main(void) {
    char foo = 'c';

    switch(foo)
    {
        printf("Cant Touch This\n");   // This line is Unreachable

        case 'a': printf("A\n"); break;
        case 'b': printf("B\n"); break;
        case 'c': printf("C\n"); break;
        case 'd': printf("D\n"); break;
    }

    return 0;
}

It seems that the printf at the top of the switch statement is valid, but also completely unreachable.

I got a clean compile, without even a warning about unreachable code, but this seems pointless.

Should a compiler flag this as unreachable code?
Does this serve any purpose at all?

8条回答
倾城 Initia
2楼-- · 2020-05-11 11:48

It is possible to implement a "loop and a half" with it, although it might not be the best way to do it:

char password[100];
switch(0) do
{
  printf("Invalid password, try again.\n");
default:
  read_password(password, sizeof(password));
} while (!is_valid_password(password));
查看更多
何必那么认真
3楼-- · 2020-05-11 11:51

Assuming you are using gcc on Linux, it would have given you a warning if you're using 4.4 or earlier version.

The -Wunreachable-code option was removed in gcc 4.4 onward.

查看更多
登录 后发表回答