Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in switch case if we write "default" as any word or single letter it does not throw an error

In a switch, if we write any word or single letter instead of default it does not throw an error. e.g.

switch(10)
{
    case 1:
    break;

    hello:
    break;
}

It runs without throwing an error.

Can anyone explain how this works?

like image 425
Pratik Avatar asked Nov 15 '12 05:11

Pratik


2 Answers

It is compiling because hello: is a label and thus can be the destination of a goto. When I compiled this I got warnings about an unreferenced label (since I did not have a goto)

Here is an example you could throw in LINQPad - you will notice that it prints both "1" and "hello":

switch(1)
{
    case 1:
        "1".Dump();
        goto hello;
    break;

    hello:
        "hello".Dump();
        break;
}
like image 91
pstrjds Avatar answered Oct 12 '22 15:10

pstrjds


It's unrelated to the switch statement. It's a label identifier for the (rarely-used due to being bad practice) goto statement.

goto something2;
something1:
    Console.WriteLine("world");
    goto done;
something2:
    Console.WriteLine("hello");
goto something1;
done:
like image 34
McGarnagle Avatar answered Oct 12 '22 15:10

McGarnagle