Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaration of a variable inside a swich case

Tags:

c

Why do I get a warning when I declare the same variable name inside different cases of a switch-case.

switch()
{
   case 1:
     int a;
   break;

   case 2:
     int a;
   break;

}

Is there a way to do this without getting a warning. (Without putting it before the switch - case)

like image 902
schanti schul Avatar asked Dec 07 '22 12:12

schanti schul


1 Answers

The reason is that the lexical scope of both declarations is the entire switch body; all the cases share that scope.
That is, in terms of lexical scope, it's like writing

{
    int a;
    int a;
}

The solution is to enclose the declarations in another braced scope.

switch(whatever)
{
   case 1:
   {
     int a;
     break;
   }

   case 2:
   {
     int a;
     break;
   }
}

(Whether you put the break inside or outside the braces is mostly a matter of taste. I prefer to include the entire case.)

This works for the same reason that this "switch-free" snippet works:

{
    {
        int a;
    }
    {
        int a;
    }
}
like image 84
molbdnilo Avatar answered Dec 31 '22 02:12

molbdnilo