• Register
+2 votes
13 views

Problem:

Getting an error while I was working with a switch statement in c++. I do have a 200 lines code that I can’t share with you for obvious reason. I am sharing the switch-statement block that produces the error in my program. The error I am getting is: cannot jump from switch statement to this case label c++

switch(foo) {
  case 1:
    int i = 42;
    dostuff(i);
    break;
  case 2:
    dostuff(i*2); 
}

Any possible solution will be admitted with thanks.

 

ago by (5.9k points)  

1 Answer

+2 votes

Solution:

You need to understand the characteristics of the switch-statement very clearly. 

In switch-statement, every case checks the individual and original condition. For every false statement, it moves forward and for a true condition, it stops checking and break the loop.

The problem occurred when you used the uninitialized variable in your second case within the same block. You need to initialize that variable in every case or make another block for the second case. Like this:

switch(foo) {
  case 1:
    {
        int i = 42; 
        dostuff(i);
        break;
    }
  case 2:
    dostuff(123);
}

I hope I am able to clear the things to you.
Thanks.

ago by (17.7k points)  
...