2

I know lot of questions stackoverflow on this topic one but I did't find answer to this one.

struct message
{
    int  myint;
};

int main(void)
{
  switch(1)
  {
    case 0:
      break;
    case 1:
      int i; // this is fine, but int i = 10; is compile error
      break;
    default:
      break;
  }
  return 0;
}

Logically speaking why is defining variable and initializing it with some value is different than just defining variable for 'case labels'?

JamesWebbTelescopeAlien
  • 3,547
  • 2
  • 30
  • 51
  • 2
    The second question in the related section on the right: http://stackoverflow.com/questions/92396/why-cant-variables-be-declared-in-a-switch-statement?rq=1 – chris Aug 05 '16 at 06:21
  • @chris, interesting post. BTW, does it answer why simple `int i;` works? I read first few of high voted answers, but couldn't find a definitive explanation. – iammilind Aug 05 '16 at 06:27
  • @iammilind, Yes, because there's no initialization being skipped. [This answer](http://stackoverflow.com/a/92730/962089) goes more into that. – chris Aug 05 '16 at 06:34
  • Your [this answer](http://stackoverflow.com/questions/92396/why-cant-variables-be-declared-in-a-switch-statement/92730#92730") is what I'm looking for – JamesWebbTelescopeAlien Aug 05 '16 at 17:11

1 Answers1

1

To define a variable inside a switch statement in C++ you need to use the braces:

int main(void)
{
  switch(1)
  {
    case 0:
      break;
    case 1:
    {  //added brace
      int i=10;
      break;
    }  //added brace
    default:
      break;
  }
  return 0;
}

here the link to C++ shell