Sign in to follow this  

switch and if

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

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 this post


Link to post
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

Share this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this