Error jump to case label default

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 int main() { int choice;...

JohannesD’s answer is correct, but I feel it isn’t entirely clear on an aspect of the problem.

The example he gives declares and initializes the variable i in case 1, and then tries to use it in case 2. His argument is that if the switch went straight to case 2, i would be used without being initialized, and this is why there’s a compilation error. At this point, one could think that there would be no problem if variables declared in a case were never used in other cases. For example:

switch(choice) {
    case 1:
        int i = 10; // i is never used outside of this case
        printf("i = %dn", i);
        break;
    case 2:
        int j = 20; // j is never used outside of this case
        printf("j = %dn", j);
        break;
}

One could expect this program to compile, since both i and j are used only inside the cases that declare them. Unfortunately, in C++ it doesn’t compile: as Ciro Santilli 包子露宪 六四事件 法轮功 explained, we simply can’t jump to case 2:, because this would skip the declaration with initialization of i, and even though case 2 doesn’t use i at all, this is still forbidden in C++.

Interestingly, with some adjustments (an #ifdef to #include the appropriate header, and a semicolon after the labels, because labels can only be followed by statements, and declarations do not count as statements in C), this program does compile as C:

// Disable warning issued by MSVC about scanf being deprecated
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

#ifdef __cplusplus
#include <cstdio>
#else
#include <stdio.h>
#endif

int main() {

    int choice;
    printf("Please enter 1 or 2: ");
    scanf("%d", &choice);

    switch(choice) {
        case 1:
            ;
            int i = 10; // i is never used outside of this case
            printf("i = %dn", i);
            break;
        case 2:
            ;
            int j = 20; // j is never used outside of this case
            printf("j = %dn", j);
            break;
    }
}

Thanks to an online compiler like http://rextester.com you can quickly try to compile it either as C or C++, using MSVC, GCC or Clang. As C it always works (just remember to set STDIN!), as C++ no compiler accepts it.

  1. the switch Statement in C++
  2. Fix the Jump to case label Error in the switch Statement in C++

Jump to Case Label in the switch Statement

This article will discuss the use of switch statements in C++. Moreover, it will discuss errors that may arise while using the switch statement, including the Jump to case label error.

the switch Statement in C++

The switch statement evaluates a given Boolean or integer expression and executes the statement(s) associated with the cases based on the evaluation of the given expression. It is the best alternative to the lengthy if-else-if statements as it reduces the code length and enhances clarity.

In C/C++, the following syntax is used for the switch statement to perform the evaluation.

Syntax:

switch(exp) {
  case a:
    // Block of code
    break;
  case b:
    // Block of code
    break;
  default:
    // Block of code
}

The switch statement works in the following way:

  • The expression is evaluated once in the switch statement.
  • The case value is compared to the switch value.
  • After evaluating the switch expression with a case statement, the block of code subsequent to the matched case is executed if the condition is true.
  • The break and default keywords are optional with the switch statement. We’ll discuss these in detail at the end of this tutorial.

Suppose we want to calculate the weekday name from the weekday number.

Example Code:

#include <iostream>
using namespace std;

int main() {
  int weak_day = 3;
  switch (weak_day) {
  case 1:
    cout << "Monday";
    break;
  case 2:
    cout << "Tuesday";
    break;
  case 3:
    cout << "Wednesday";
    break;
  case 4:
    cout << "Thursday";
    break;
  case 5:
    cout << "Friday";
    break;
  case 6:
    cout << "Saturday";
    break;
  case 7:
    cout << "Sunday";
    break;
  default:
    cout << "Invalid input";
  }
}

Output:

the break Keyword

The break keyword is used with a switch statement to skip the remaining cases of the switch body after a given case is met.

In the above example, when the switch statement is evaluated and meets the criteria in case 3, it skips the remaining code block of the switch body due to the break; statement.

the default Keyword

The default keyword is used with the switch statement to execute a specified block of code when none of the cases is met in the given switch statement.

Let’s look at the following example, which demonstrates using the default keyword in the switch statement.

Example Code:

#include <iostream>
using namespace std;

int main(){

int a = 4;
switch (a) {
  case 6:
    cout << "Value of a is 6";
    break;
  case 7:
    cout << "Value of a is 7";
    break;
  default:
    cout << "The number is other than 6 or 7";
}
}

Output:

The number is other than 6 or 7

In this example, we have specified the value of the integer variable as 4, but none of the cases will satisfy the given condition during the execution. Therefore, the default block is executed.

Fix the Jump to case label Error in the switch Statement in C++

A common error that may arise while using the switch statement is a Jump to case label error. The error occurs when a declaration is made within/under some case label.

Let’s look at the following example to understand the issue:

#include <iostream>
using namespace std;

int main() {
  int a = 1;
  switch (a) {
    case 1:
      int i=66;
      cout<<i;
      break;

    case 2:
      cout<<i*3;
      break;
    default:
      cout << "Looking forward to the Weekend";
  }
  return 0;
}

In the above example, when we initialize i=66 in case 1: and execute the code. The code generates an error Jump to case label as the value of i is visible to the other cases.

A case is just a label and therefore doesn’t restrict the scope of the code written next to it. Hence, if case 2 is executed during execution, i will be an uninitialized variable.

So, a strongly typed language like C++ will never allow this to happen. Thus, it generates a compile-time error.

The scope delimiters {} within case 1 can overcome this scope issue and help execute the code without error.

#include <iostream>
using namespace std;

int main() {
  int a = 1;
  switch (a) {
    case 1:{
      int i=66;
      cout<<i;
      break;
    }
    case 2:
      cout<<"value does not exist";
      break;
    default:
      cout << "Looking forward to the Weekend";
  }
  return 0;
}

A compiler, the compiler error error: jump to case label [- fpermissive], the error: crosses initialization of 'XXXX' </ code>, to simple combing the related content

I. Problem code

int main()
{
  int test = 2;
  switch(test)
  {
    case 1:
      int i = 1;  
      cout << i;
      break;
    case 2:
      cout << i;  
      break;
    default:
      cout << "error" << endl;
  }
}

//test.cpp: In function 'int main()':
//test.cpp: error: jump to case label [-fpermissive]
//   case 2:
//        ^
//test.cpp: error:   crosses initialization of 'int i'
//    int b = 1;
//test.cpp: error: jump to case label [-fpermissive]
//   default:
//   ^
//test.cpp:11:8: error:   crosses initialization of 'int i'
//    int b = 1;

As can be seen from the above code, since there is no separate block in switch to qualify the declaration period of variable I, the scope of the variable is the initialization point to the end of switch. In this case, the compiler will report an error because we are not sure whether this variable will be used in other cases and whether it was initialized before it was used. For example, if test has a value of 2 and case 2 is executed directly, an undefined variable will cause an exception. This is a compiler error crosses initialization </ code>.
After inspection, it is found that the compiler will report an error
no matter whether the other branches contain defined variables or not, as long as the variables are not braced in the case.

int main()
{
  int test = 2;
  switch(test)
  {
    case 1:
      int i = 1; 
      cout << i;  
      break;
    case 2:
      cout << 3; 
      break;
    default:
      cout << "error" << endl;
  }
}

//test.cpp: In function 'int main()':
//test.cpp: error: jump to case label [-fpermissive]
//   case 2:
//        ^
//test.cpp: error:   crosses initialization of 'int i'
//    int i = 1;
//test.cpp: error: jump to case label [-fpermissive]
//   default:
//   ^
//test.cpp: error:   crosses initialization of 'int i'
//    int i = 1;

The code of case 1 is enclosed with {}, and the scope of variable I is clearly set to avoid access by other cases
2. The scope of variable I is put outside the switch, and every case in the switch can be accessed
The
switch statement is a kind of goto statement, so goto has the same properties. The following goto statement will not be executed, variable I will definitely be defined, but will report the same error as above. This means that there can be no variables between goto and the tag. Variables must appear before the goto or after the tag.

int main()
{
    if(0)
    {
        goto end;
    }

    int i = 1;

    end:
       cout << i;
}

//test.cpp: In function 'int main()':
//test.cpp error: jump to label 'end' [-fpermissive]
//   end:
//   ^
//test.cpp error:   from here [-fpermissive]
//          goto end;
//               ^
//test.cpp: error:   crosses initialization of 'int i'
//     int i = 1;

In the above example, it is possible to initialize a variable before the goto tag or after the end tag

Read More:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <cstdlib>
#include <iostream>
#include <stdio.h>
int vvod(int **l);
int sum(int *m, int n);
int asum(int *m, int n);
 
using namespace std;
 
int main()
{
   int boq;
  do{ 
 system("cls");
 printf("ttt********MENU*********nn");
  printf("1. Mechn");
  printf("2. oqing n");
  printf("3. bilmiman torisi n"); 
  printf("4. amizi ying n");
  printf("nnnzdelayte vash vibor:t");
    int mech;
    scanf("%d", &mech);
    switch(mech){
                 case 1:
 
for ( int i = 0; i < 10; i++ ) {
    printf("tttumniy moln");
}
break;
case 2:
  int *x, *y, *z;
 
  printf("zapolnite massiv X n");
  int Nx = vvod(&x);
  int sumx = sum(x, Nx);
  int asumx = asum(x, Nx);
 
  printf("zapolnite massiv Y n");
  int Ny = vvod(&y);
  int sumy = sum(y, Ny);
  int asumy = asum(y, Ny);
 
  printf("zapolnite massiv Z n");
  int Nz = vvod(&z);
  int sumz = sum(z, Nz);
  int asumz = asum(z, Nz);
  printf("ttsumma polojitelnix chiseln");
  printf("SumX = %dnSumY = %dnSumZ = %dnn", sumx, sumy, sumz);
  printf("ttsumma otricatelnix chiseln");
  printf("aSumX = %dnaSumY = %dnaSumZ = %dn", asumx, asumy, asumz);
     break;
      case 3:
      printf("qandayn");
      break;
      default:
              printf("net takoy operaciin");
              break;    
}
      printf("xotite eshe raz najmite 1:n", boq);
              scanf("%d", &boq);
}while(boq==1);
system("PAUSE");
puts("konets");
    return 0;
}
 
////////////////////////////////////////////////////
int vvod(int **l) {
  int n;
  printf("tt ukajite razmer massiva: ");
  scanf("%d", &n);
  int *m = new int[n];
  for (int i = 0; i < n; i++) {
     printf("element%d: ", i + 1);
     scanf("%d", &(m[i]));
  }
  *l = m;
  return n;
}
 
int sum(int *m, int n) {
  int sum = 0;
  for (int i = 0; i < n; i++) 
      if (m[i] > 0) 
         sum += m[i];
      
  
  return sum;
}
 
int asum(int *m, int n) {
  int sum = 0;
  for (int i = 0; i < n; i++) 
      if (m[i] < 0) 
         sum += m[i];
      
  
  return sum;
}

Обнаружил для себя такую неожиданную вещь: код

switch (a) {
    case 1:
        std::string alfa;
        break;
    case 2:
        break;
    default:
        break;
}

не компилируется из-за объявления переменной класса string. Компилятор выдает, что не может прыгнуть к следующей метке:

1.cpp:16:9: error: cannot jump from switch statement to this case label
    default:
    ^

Но почему так? Почему, если объявить, например, переменную типа int, то все в порядке?

Ответы (2 шт):

Смотрите — а что ему делать, если вы получите a==2 и при этом решите в ветви обратиться к этой переменной alfa? Инициализировать ее? нет?

Во избежание таких фокусов — перепрыгивания через инициализацию — это считается ошибкой.

Просто возьмите переменную в фигурные скобки, чтоб ограничить область видимости:

switch (a) {
    case 1:
        {
            std::string alfa;
        }
        break;
    case 2:
        break;
    default:
        break;
}

→ Ссылка

Автор решения: αλεχολυτ

Вариант с int var; работает потому, что такая запись не приводит к какой-либо инициализации. Стоит добавить инициализацию, как также получим ошибку «перепрыгивания». std::string же сложный класс со своим конструктором, поэтому явная инициализация не требуется и всё равно будет вызван конструктор по умолчанию.

При этом для int остаётся возможность присвоить переменной значение и работать с ней как ни в чём ни бывало в любой ветке ниже определение переменной.

→ Ссылка

Most Android users might not encounter this problem. But, for those who want to make the best of their Android devices, this could be a real nightmare. “Cannot jump from switch statement to this case label” error is usually encountered by Android programmers who are using C or C++ to build their app.

For those who don’t know yet, with your Android device, you can do whatever you want. Since it’s open software, you can make adjustments and modifications, as well as install your created apps on your phone.

Especially with Android Studio, the official Integrated development system (IDE) for Android applications from Google, you can easily create high-quality apps. It has custom-tailored tools for Android developers, so you can easily code, edit, debug, test, and so on.

Although the official language of Android development is Java, it’s possible to develop C and C++ apps. With the Android Native Development Kit (NDK) you can use C++, but Google isn’t promoting this method — hence, the Android Studio app. Other programming languages Android developers can use are C#, BASIC, PhoneGap, and more. On the side note, you also need to learn XML for the UI-related stuff.

Why Use C++ for Android Apps?

Even though C++ isn’t recommended for Android app development, still, a lot of enthusiastic Android developers prefer this over Java. One of the most obvious reasons is that when using native code on Android, you can experiment on the complexity of the app you make. For seasoned developers, they prefer C++ over Java because of the following:

Well-known Android Language

Google has Android NDK before. And, while it’s not useful for a great number of Android apps, it’s useful for CPU-intensive apps and game engines.

Existing Game Source Code

There are tons of free content and open-source game engines out there built in C++. While not all game apps are made in C++, there is a handful of them. And, you can put some things together to come up with a great Android app.

Faster Code

Famous apps like Facebook, Office, Skype, and even the game Clash of Clans use C++ for cross-platform development. The advantage of C++ is that it doesn’t have a standard user interface. In some cases, Java could be much faster to code, but it’s the native code that dominates the areas of gaming, physics, signal processing, etc. While this is also possible with JN! in Java, it may take time. Hence, C++ coding is still faster.

Yes, Java is an excellent and versatile programming language, but for Android development, C++ has more interesting advantages. Aside from the three reasons above, there are still a few more. C++ occupies a smaller memory footprint. Since it’s a superset of C, you can use most C programs to compile your code or reuse some C software.

Last, Java source code is compiled to bytecode in .jar files. During runtime, the JVM will load the .jar file bytecode and compile it to machine code. For C++ on the other hand, you can easily and quickly compare it with different available software.

Understanding Switch Statement and Case Label

Before discussing the solution to this problem, you must know the characteristics of the switch statement by heart. It’s a selection statement that is often used as an alternative for the if-else statement. This includes one or more switch sections. And, each switch section usually has one or more case labels (case or default label). Check below for a sample code block so you can visualize what the problem is.

You must understand how the switch statement works. For the false statement, it’ll move forward, but for the true statement, it’ll stop and break the loop. With the switch-statement, you can inevitably use several curly braces if you have different cases. You must be careful of these braces. When you’ll initialize a variable in one case, then, you use it in the succeeding case, the error also occurs. You must use explicit {} blocks to prevent this. See the example below.

Solution

As you can see, this problem isn’t a big deal. All you got to do is to write your code properly and put the curly braces in the right place. Even if you have several lines of codes and have different case labels in your switch-statement, the ‘cannot jump from switch statement to this case label’ error is just a problem of the curly braces.

Use Curly Braces

For every case label, it’s safe if you will enclose the condition in each case with a pair of curly braces. This simply means you need to wrap each case label explicitly. Now, the problem would be, there will be too many curly braces and you don’t know the proper pairing anymore. There are C++ editors and compilers that let you know upfront if you have missed an open or close curly brace. Using these programs will allow save you more time debugging and editing the codes.

Initialize Variable in Every Case Label

Define and initialize variables in each case level. Although you have declared the variable in the first case, if you’ll use it in the second, it will return an error. Especially with the curly braces, it’ll limit the scope per case label. So, if you need to use variables, have it in each case.

The Final Say

If you’re an experienced C++ developer and you want to break (maximize the potential of) your Android mobile phone, you can make Android apps in C++ without a problem. Especially with Google’s release of the Android Studio and the support it has for native language, you can make Android apps even with zero knowledge in Java.

Unfortunately, the most prominent issues on C++ is the ‘cannot jump from switch statement to this case level’ error. It may seem technical, but an increasing number of expert programmers find it’s just an issue on the curly braces. That’s all!

The curly braces may seem to be small things, but they’re powerful enough to make or break your code. You must know its usage and its proper location in the code to build an Android app that can change your life forever.

I am a Software developer with approx 4 years of experience in building various responsive and beautiful websites and apps.

Language: Ruby, Java, HTML/CSS, Android
Frameworks: Ruby on Rails, Hosting: Heroku, Godaddy
Database: Mysql, Postgres, Mongo, Oracle
Also please look on my stack overflow profile.

[Исключение C ++] ошибка: перейти к метке регистра [-fpermissive]

Автор: blue_smile
ссылка:https://www.jianshu.com/p/254abfa7caed

При компиляции программы компилятор сообщает об ошибке: перейти к метке регистра [-fpermissive], ошибка: пересекает инициализацию «xxxx», просто отсортируйте соответствующий контент

Во-первых, код проблемы

int main()
{
  int test = 2;
  switch(test)
  {
    case 1:
      int i = 1; // После инициализации i он всегда существует, пока переключатель не закончится
      cout << i;
      break;
    case 2:
             cout << i; // i не инициализирован
      break;
    default:
      cout << "error" << endl;
  }
}
 # Сообщение об ошибке выглядит следующим образом
//test.cpp: In function 'int main()':
//test.cpp: error: jump to case label [-fpermissive]
//   case 2:
//        ^
//test.cpp: error:   crosses initialization of 'int i'
//    int b = 1;
//test.cpp: error: jump to case label [-fpermissive]
//   default:
//   ^
//test.cpp:11:8: error:   crosses initialization of 'int i'
//    int b = 1;

2. Описание

Как видно из приведенного выше кода, поскольку в коммутаторе нет отдельного блока области для ограничения жизненного цикла переменной i, область действия переменной находится от точки инициализации до конца коммутатора. Здесь, поскольку мы не можем определить, будет ли эта переменная использоваться в других случаях и инициализирована ли переменная перед использованием, компилятор сообщит об ошибке. Например: тестовое значение равно 2, если случай 2 выполняется напрямую, произойдет исключение, если переменная не определена. Это также причина, по которой отчеты компилятора пересекают инициализацию.
После проверки было обнаружено, что независимо от того, содержат ли другие ветви определенные переменные, пока регистр содержит переменные без скобок, компилятор сообщит об ошибке.

int main()
{
  int test = 2;
  switch(test)
  {
    case 1:
      int i = 1; 
      cout << i;  
      break;
    case 2:
             cout << 3; // также сообщит об ошибке
      break;
    default:
      cout << "error" << endl;
  }
}
 # Сообщение об ошибке выглядит следующим образом
//test.cpp: In function 'int main()':
//test.cpp: error: jump to case label [-fpermissive]
//   case 2:
//        ^
//test.cpp: error:   crosses initialization of 'int i'
//    int i = 1;
//test.cpp: error: jump to case label [-fpermissive]
//   default:
//   ^
//test.cpp: error:   crosses initialization of 'int i'
//    int i = 1;

3. Способ модификации

1. [Уменьшите область видимости] Заключите код случая 1 с {}, четко установите область действия переменной i и избегайте доступа к другим случаям
2. [Расширьте область действия] Поместите переменную i за пределы переключателя, и будет доступен каждый случай в переключателе.

Четыре, глубокое понимание

Оператор switch является своего рода оператором goto, поэтому goto имеет те же свойства.Следующий оператор goto не будет выполнен, и переменная i будет определена, но будет сообщена та же ошибка, что и выше. Это показывает, что переменные не могут появляться между переходом и меткой. Переменная должна стоять перед переходом или после метки.

int main()
{
    if(0)
    {
        goto end;
    }

    int i = 1;

    end:
       cout << i;
}
 # Сообщение об ошибке выглядит следующим образом:
//test.cpp: In function 'int main()':
//test.cpp error: jump to label 'end' [-fpermissive]
//   end:
//   ^
//test.cpp error:   from here [-fpermissive]
//          goto end;
//               ^
//test.cpp: error:   crosses initialization of 'int i'
//     int i = 1;

В приведенном выше примере можно разместить инициализацию переменной перед тегом goto или после конечного тега.

Neil Zanella


  • #1

Hello,

Does anyone know what the following g++ compiler error message means:

error: jump to case label

I get this error when switching two case labels together with their bodies.
I have no setjmp/longjmp or gotos in my program.

Thanks,

Neil

Advertisements

Bill Seurer


  • #2

Neil said:

I get this error when switching two case labels together with their bodies.

Explain that further or better yet post the offending code.

James Gregory


  • #3

Hello,

Does anyone know what the following g++ compiler error message means:

error: jump to case label

I get this error when switching two case labels together with their bodies.
I have no setjmp/longjmp or gotos in my program.

Perhaps the problem is «jump to case label croses initialization»?

The following is not allowed:

switch (a)
{
case 1:
int a = 6;
//stuff
break;

case 2:
//stuff
break;
}

The following is allowed:

switch (a)
{
case 1:
{
int a = 6;
//stuff
}
break;

case 2:
//stuff
break;
}

James

Neil Zanella


  • #4

Bill Seurer said:

Explain that further or better yet post the offending code.

Sure I will. Here is the code. Uncommenting the lines for case 1 produces
the compiler error message. Furthermore, out of curiosity, as an unrelated
matter, I am quite interested in knowing how come the program starts looping
when some large number is entered.

Thanks,

Neil

#include <iostream>

int main() {
unsigned int x; do {
std::cout << «Please enter an integer: » << std::flush;
std::cin >> x;
switch (x) {
case 0:
std::cout << «Hello!» << std::endl;
break;
default:
unsigned int y = ++x;
std::cout << «You could have entered » << y;
std::cout << «. Why didn’t you?» << std::endl;
break;
//case 1:
// std::cout << «What??? You entered one?» << std::endl;
// break;
}
} while (x != 0);
}

Jacek Dziedzic


  • #5

Neil said:

Sure I will. Here is the code. Uncommenting the lines for case 1 produces
the compiler error message.

Try moving them before the ‘default’

Furthermore, out of curiosity, as an unrelated
matter, I am quite interested in knowing how come the program starts looping
when some large number is entered.

cin.fail() is set and all subsequent «>>» operations are ignored,
with x unmodified every time. Hence, if x happened to be non-zero,
the loop iterates infinitely.

Thanks,

Neil

#include <iostream>

int main() {
unsigned int x; do {
std::cout << «Please enter an integer: » << std::flush;
std::cin >> x;
switch (x) {
case 0:
std::cout << «Hello!» << std::endl;
break;
default:
unsigned int y = ++x;
std::cout << «You could have entered » << y;
std::cout << «. Why didn’t you?» << std::endl;
break;
//case 1:
// std::cout << «What??? You entered one?» << std::endl;
// break;
}
} while (x != 0);
}

HTH,
— J.

Neil Zanella


  • #6

Jacek Dziedzic said:

Try moving them before the ‘default’

Thank you for your reply…
I know that works but that doens’t really explain the nature of the problem.

Regards,

Neil

Advertisements

Buster


  • #7

Neil said:

Thank you for your reply…
I know that works but that doens’t really explain the nature of the problem.

Please don’t top-post.

James Gregory is right. The ‘jump’ in the error message is the computed
goto effected by the switch statement. When x = 1, the switch acts like
this:

goto case_label_1;
// …
unsigned int y = ++ x;
// …
case_label_1:
// here y is uninitialized

The problem is that the initialization of y is skipped when x == 1.
When the «case 1:» label is reached, stack space has been allocated for
y but its value has not been initialized. This is not allowed.

The general way round this situation is to make the scope of y smaller
by adding braces:

switch (x)
{
default:
unsigned z; // this is OK since z is uninitialized
{
unsigned y = x + 1;
// …
}
case 1:
z = 2;
// …
// cannot refer to y here so no problem with y’s initialization
}

Понравилась статья? Поделить с друзьями:
  • Error jtag scan chain interrogation failed all ones
  • Error json parse error undefined
  • Error json decode stream url
  • Error jpeglib h not found
  • Error joining network cannot connect to zerotier service