# switch and if

This topic is 4574 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I can define variable in if ,but it does not in switch. why?

##### Share on other sites
You'll need to define another scope block for that, I believe:

switch(value)
{
case 1:
{
int my_var;
}
break;
}

switch(value)
{
case 1:
int my_var;
break;
}

##### Share on other sites
You cannot jump into a scope past a variable definition. Since the switch construct in C++ involves jumping to case labels, you can only write variable definitions in the switch scope after the last case (or default) label.

You can, of course, add another scope within the switch scope. This would work:

switch( foo ) {case 0:   {    int baz;    frobnicate(baz);  }  break;default: assert( false );}

##### Share on other sites
Actually, only jumping past a variable initialization is forbidden. I only found out about that a while ago. So, you can't do this:
switch(foo){ case 0:  break; case 1:  int i = 12;  break;}

But, you can do this:
switch(foo){ case 0:  break; case 1:  int i;  i = 12;  break;}

Or this:
switch(foo){  int i; case 0:  i = 10;  break; case 1:  i = 42;  break;}

I know, it doesn't seem to make any sense, but that's the way it is :P

1. 1
2. 2
3. 3
Rutin
22
4. 4
JoeJ
16
5. 5

• 14
• 29
• 13
• 11
• 11
• ### Forum Statistics

• Total Topics
631774
• Total Posts
3002292
×