Use of local variables in case statement

A

A

My compiler complains (probably for a good reason) that it cannot use local
variable in case statement.

But it is a mess if I declare it outside case. So I would like to keep it
local.

Is there a way to override this compiler behaviour or to write code
differently so that it doesn't trigger compiler error:

For example:

switch (condition)
{
case 0: // do something
break;
case 1: int i = 0; // This is where compiler says "case bypasses
init of local variable"
// use i here
break;
}
 
A

A

hmm... looks like i solved this one myself by inserting braces on case 1.


switch (condition)
{
case 0: // do something
break;
case 1: {
int i = 0;
// use i here
}
break;
}

Perhaps someone knows some other variation/solution to this?
 
J

Jorgen Grahn

You have the correct solution. You might want to seriously consider
putting the block that goes in the case statement into its own function:

void case1func() {
int i = 0;
// use i here
}

...

switch (condition) {
case 0:
case0func();
break;
case 1:
case1func();
break;
}

Depends very much on what he's doing. If it's like most switches I
see in real code, breaking it into many tiny functions would create a
world of spaghetti pain.

Do what makes sense for the problem at hand.

/Jorgen
 
Ö

Öö Tiib

My compiler complains (probably for a good reason) that it cannot use local
variable in case statement.

But it is a mess if I declare it outside case. So I would like to keep it
local.

Is there a way to override this compiler behaviour or to write code
differently so that it doesn't trigger compiler error:

For example:

switch (condition)
    {
    case 0: // do something
            break;
    case 1: int i = 0;        // This is where compiler says "case bypasses
init of local variable"
            // use i here
            break;
    }

Maybe like this:

switch (condition)
{
default:
assert( !"buggy switch" );
break;
case 0:
// do something
break;
case 1:
{
int i = 0;
// use i here
}
break;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top