Lightfoot8 wrote...
case x:
//code
int y= 5;
// more code
will not work.
For this case you need to define the variable outside the case statement. For example:
int nCheck = d20();
int nNumber;//<---Declaring variable outside the switch/case
switch( nCheck )
{
case 1:
nNumber = 1;
break;
case 2:
nNumber = 5;
break;
}
The compiler will freak out if you do this:
int nCheck = d20();
switch( nCheck )
{
case 1://<------No brackets!!
int nNumber = 1;//<---Declaring inside the case!!
break;
case 2:
int nNumber = 5;
break;
}
You'll get this error:
ERROR: SKIPPING DECLARATION VIA "case" STATEMENT DISALLOWED.
Notice how I declared the variables INSIDE the case and also notice the case does not use brackets. Compiler will tell you to declare outside the switch/case. What you can do to work around this is either declare the variable outside the switch/case or add brackets to the case. For example:
int nCheck = d20();
switch( nCheck )
{
case 1:
{//<----Notice I placed brackets!
int nNumber = 1;
break;
}
case 2:
{
int nNumber = 5;
break;
}
}
That will compile fine. So if you need to declare a variable inside the case, add brackets to it as in this last example.
Modifié par Dagesh, 14 octobre 2010 - 03:21 .