[Solved-2 Solutions] Error: Jump to case label
Error Description:
Error: Jump to case label
Solution 1:
- The problem is that variables declared in one case are still visible in the subsequent cases unless an explicit { } block is used, but they will not be initialized because the initialization code belongs to another case.
- In the following code, if foo equals 1, everything is ok, but if it equals 2, we'll accidentally use the i variable which does exist but probably contains garbage.
switch(foo) {
case 1:
int i = 42; // i exists all the way to the end of the switch
dostuff(i);
break;
case 2:
dostuff(i*2); // i is *also* in scope here, but is not initialized!
}
click below button to copy the code. By c++ tutorial team
- Wrapping the case in an explicit block solves the problem:
switch(foo) {
case 1:
{
int i = 42; // i only exists within the { }
dostuff(i);
break;
}
case 2:
dostuff(123); // Now you cannot use i accidentally
}
click below button to copy the code. By c++ tutorial team
Solution 2:
- Declaration of new variables in case statements is what causing problems. Enclosing all casestatements in {} will limit the scope of newly declared variables to the currently executing case which solves the problem.
switch(choice)
{
case 1: {
// .......
}break;
case 2: {
// .......
}break;
case 3: {
// .......
}break;
}