Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "defau4t" legal in a switch statement? [duplicate]

I came up with this program in some other site and thought of trying it, here's the program:

#include <stdio.h>
int main()
{
    int a=10;
    switch(a)
    {
         case '1': printf("one");
                   break;
         case '2': printf("two");
                   break;
         defau4t:  printf("none");
    }
    return 0;
}

Suprisingly enough, this compiles without errors or warnings. How is this possible? Isn't there an error on keyword "default"?
Could anyone explain this behaviour?

like image 668
nj-ath Avatar asked Sep 16 '14 12:09

nj-ath


2 Answers

The token is not considered to be a keyword at all. This is a goto jump mark named "defau4t" pointing at otherwise dead code (after the break; of case '2':)...

Try this for laughs (and an endless loop):

switch(a)
{
     case '1': printf("one");
               break;
     case '2': printf("two");
               break;
     defau4t: printf("none");
     default: goto defau4t;
}
like image 53
DevSolar Avatar answered Nov 19 '22 16:11

DevSolar


One flaw with the switch statement is that you can wildly jump in and out of them using goto. At any point inside the switch (or outside it for that matter), you can place a label, that you can jump to with goto. Of course, that is very bad practice as it leads to spaghetti code.

So defau4t: is merely a label, and labels can be placed pretty much anywhere inside function bodies.

like image 43
Lundin Avatar answered Nov 19 '22 17:11

Lundin