. Advertisement .
..3..
. Advertisement .
..4..
I get the “Error: Jump to case label in switch statement in C++” error as the title says. How can I fix it so the error goes away? Here is my detail:
#include <iostream>
int main()
{
int choice;
std::cin >> choice;
switch(choice)
{
case 1:
int i=0;
break;
case 2: // error here
}
}
When I operated it, I received the error text:
Error: Jump to case label.
I appreciate any help from you.
The cause:
This problem because declaration of variables in
case
will be shown in subsequentcase
unless HTML13 blocks are used. However, they won’t be initialized because the initialization code belongs to anothercase
.Solution:
You can check whether
foo
equals 1 by the following code. If it equals 1, all is fine but if it equals 2, then we’ll accidentally usei
, it exists but contains garbage.You can solve this probblem by wrapping the case in an explicit block:
Moreover, you also can describe a more fancy version of
goto
by usingswitch
statements. Below is an analogous piece of code that has the same issue, but it uses agoto
rather than aswitch
.Problems are caused by the declaration of new variables within case statements. This problem can be solved by enclosing all
case
{}
statements.