4

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)

schanti schul
  • 681
  • 3
  • 14

3 Answers3

11

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;
    }
}
molbdnilo
  • 64,751
  • 3
  • 43
  • 82
3

Declare your variables inside a new code block. Start a new code block with {

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

   case 2:
   {
     int a;
      break;
   }
}
Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551
1

There are two reasons.

  • Everything inside the { ... } of a switch resides in the same scope, unless you add further local scopes inside it. So you can't have two variables with the same name, for the same reason as you can't have:

    int main (void) 
    {
      int a; int a; // will not compile
    }
    
  • Grammatically, case x: works like a label. In the C syntax, it is formally called labeled-statement and a labeled-statement can only be followed by a statement, not a declaration. So you can't have a variable declaration directly after case x:, for the same reason as you can't have

    int main (void) 
    { 
      label: int a; // will not compile
    }
    

The best solution is to create another local scope per case. Or rename the variables.

Lundin
  • 195,001
  • 40
  • 254
  • 396