BartoszKP
BartoszKP

Reputation: 35891

What's the reason of allowing arbitrary labels inside the switch statements?

The following code compiles:

int a = 0;

switch (a)
{
    case 1:
        return;
    defau1t:      // note the typo
        return;
}

because defau1t is interpreted as a goto label.

However in the following case:

switch (a)
{
    defau1t:
        return;
}

the compiler correctly identifies the mistake:

error CS1525: Unexpected symbol defau1t', expecting}', case', ordefault:'

Why is that? What's the reason of allowing arbitrary labels inside the switch statements if it leads to (seemingly) incoherent behaviour?

Side note: The same problem can be observed for similar snippets for C++ and Java.

Upvotes: 5

Views: 204

Answers (2)

Ryan M
Ryan M

Reputation: 2112

C# works this way because this is what is in the specification. Section 8.7.2 of the C# specification defines the grammar of a switch statement. Notably, if the switch block is not empty, it must contain a switch section, and a switch section must start with a switch label, which is case <constant expression>: or default:. In your second example, you have a non-empty switch-block which does not contain a valid switch section and is thus not a valid statement.

To channel Eric Lippert a bit, disallowing labeled statements within a switch block is a language feature that would need to be conceived of, proposed, designed, specified, developed, tested, documented, and shipped. My guess is that this feature probably never made it past being conceived of.

Upvotes: 1

user743382
user743382

Reputation:

I think you're looking at this the wrong way. It's not that a special exception has been made to allow it, it's that no special exception has been made to disallow it.

There is a rule that a switch block must start with a case or default label, but other than that, any valid code can be part of the block.

Including other labels.

Disallowing this would make the language more complicated to understand, would make compilers more difficult to write, and would have some benefit, that benefit is only minor.

Upvotes: 9

Related Questions