I wrote a program which involves use of switch statements, however on compilation it shows:
Error: Jump to case label.
Why does it do that?
#include <iostream> int main() { int choice; std::cin >> choice; switch(choice) { case 1: int i=0; break; case 2: // error here } }
What does the error jump to case label mean in C++? The problem is that variables declared in one case are still visible in the subsequent case s unless an explicit { } block is used, but they will not be initialized because the initialization code belongs to another case .16-Apr-2011.
See the statement switch(choice); it is terminated by semicolon (;) – it must not be terminated. To fix this error, remove semicolon after this statement.
A case or default label can only appear inside a switch statement. The constant-expression in each case label is converted to a constant value that's the same type as condition . Then, it's compared with condition for equality.
The switch statement can include any number of case instances. However, no two constant-expression values within the same switch statement can have the same value.
The problem is that variables declared in one case
are still visible in the subsequent case
s 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! }
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 }
To further elaborate, switch
statements are just a particularly fancy kind of a goto
. Here's an analoguous piece of code exhibiting the same issue but using a goto
instead of a switch
:
int main() { if(rand() % 2) // Toss a coin goto end; int i = 42; end: // We either skipped the declaration of i or not, // but either way the variable i exists here, because // variable scopes are resolved at compile time. // Whether the *initialization* code was run, though, // depends on whether rand returned 0 or 1. std::cout << i; }
Declaration of new variables in case statements is what causing problems. Enclosing all case
statements 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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With