Error jump to case label fpermissive

I have the following error in my Calculator code and do not understand how to correct it. Please any advice would be helpful. ERROR: error: jump to case label [-fpermissive]| error:crosses

I have the following error in my Calculator code and do not understand how to correct it. Please any advice would be helpful.

ERROR:
error: jump to case label [-fpermissive]|
error:crosses initialization of ‘int sum’|
error: ‘exit’ was not declared in this scope|

CODE:

#include <iostream>
#include <cmath>
using namespace std;         
void display_menu(); 
int get_menu_choice();
void get_two_numbers(int &a, int &b);
int add(int a, int b);
int subtract(int a, int b);


int main()
 {
 int choice;

  do
   {
    display_menu();
    choice = get_menu_choice();
    int x, y;
    switch (choice)
    {
        case 1: get_two_numbers(x, y);
                int sum = add(x, y);
                cout << x << " + " << y << " = " <<  sum << endl;
                break;
        case 2: get_two_numbers(x, y);
                int diff = subtract(x, y);
                cout << x << " - " << y << " = " <<  diff << endl;
                break;
        default:;
    }

     } while (choice != 3);

     cout << "Good bye...now." << endl;

     return 0;
       }


 void display_menu()
  {
   cout << endl;
   cout << "Simple Calculator Menu" << endl;
   cout << "----------------------" << endl;
   cout << " 1. Addition (+) " << endl;
   cout << " 2. Subtraction (-) " << endl;
   cout << " 3. Quit to exit the program" << endl;
   cout << endl;
  }

 int get_menu_choice()
  {
   int choice;
   cout << "Enter your selection (1, 2, or 3): ";
   cin >> choice;

  while(((choice < 1) || (choice > 3)) && (!cin.fail()))
   {
    cout << "Try again (1, 2, or 3): ";
    cin >> choice;
    }
  if (cin.fail())
    {
      cout << "Error: exiting now ... " << endl;
      exit(1);
     }
   return choice;
    }

 void get_two_numbers(int &a, int &b)
  {
    cout << "Enter two integer numbers: ";
    cin >> a >> b;
  }


 int add(int a, int b)
  {
   return (a + b);
  }

 int subtract(int a, int b)
  {
    return (a - b);
  }

anubis1768

4 / 4 / 0

Регистрация: 23.02.2013

Сообщений: 151

1

02.05.2013, 12:33. Показов 29283. Ответов 1

Метки нет (Все метки)


Здравствуйте. Не один раз встречался с такой ошибкой. Сам не знаю, что она означает, но выправлял я ее с помощью if вместо switch — case. Так вот: здесь уже так у меня не получиться так исправить. Поясните пожалуйста, что эта ошибка означает и как ее исправить.

C++
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
#include <iostream>
#include <conio.h>
#include <vector>
#include <cstdlib>
 
enum KEYS { SPACE = 32, ENTER = 13, BACKSPACE = 8 };
 
int main(int argc, char *argv[]) {
    const int size = 200;   
    std::vector< std::string > buff( size );
    int counter = 0;
    std::string temp;   
    int key;
    
    while( counter < size ) {               
        for( int i = 0; i < counter; i++ ) {
            std::string temp2 = buff[i];
            if( temp2[temp2.size() - 1] == '~' ) {
                temp2 = temp2.substr (0, temp2.size() - 1);
                std::cout << temp2;
                std::cout << std::endl;
            } else {
                std::cout << temp2;
            }
        }
        std::cout << temp;
        
        key = getch();
        
        switch( key ) {
            case SPACE:
                buff[counter] = temp;
                std::string newStr = "";
                temp = newStr;
                counter++;
                break;
                
            case ENTER:        //вот здесь ошибка
                temp += "~";
                buff[counter] = temp;
                std::cout << std::endl;
                std::string newStr = "";
                temp = newStr;
                counter++;
                break;
                
            case BACKSPACE:
                if( temp.size() > 0 ) {
                    temp = temp.substr (0, temp.size() - 1);
                } else {
                    buff[counter] = "";
                    counter--;
                    temp = buff[counter];
                }
                break;
                
            default:
                temp += static_cast< char >( key );
        }
        
        system( "cls" );    
    }
    return 0;
}

ЗЫ компилирую с ключом fpermissive

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Croessmah

Don’t worry, be happy

17781 / 10545 / 2036

Регистрация: 27.09.2012

Сообщений: 26,516

Записей в блоге: 1

02.05.2013, 23:55

2

Если объявляете какие-то переменные в блоках case, тогда заключайте содержимое этих блоков в фигурные скобки:

C++
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
        switch( key ) {
            case SPACE:{
                buff[counter] = temp;
                std::string newStr = "";
                temp = newStr;
                counter++;
                break;
                }
                
            case ENTER:{        //вот здесь ошибка
                temp += "~";
                buff[counter] = temp;
                std::cout << std::endl;
                std::string newStr = "";
                temp = newStr;
                counter++;
                     break;
                }
                
            case BACKSPACE:
                if( temp.size() > 0 ) {
                    temp = temp.substr (0, temp.size() - 1);
                } else {
                    buff[counter] = "";
                    counter--;
                    temp = buff[counter];
                }
                break;
                
            default:
                temp += static_cast< char >( key );
        }



11



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:

[Исключение 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 или после конечного тега.

I’m sorry for the basic question, but I have a switch case where any code placed after a certain function call simply never gets called, and I’ve spent half a day looking at it, so thank you so much for your help.

Running on an Arduino UNO.

Here is the loop, and every option in the switch case after the call to moist_sensor.read() simply never gets in:


void loop() {

  while (Serial.available() > 0) {
    char val = (char)Serial.read(); // read data byte by byte and store it
    Serial.println(val);
    switch(val) {
        
      case 'O':
            digitalWrite(13, LOW);
            
            break;
      
      case 'I':
            digitalWrite(13, HIGH);
            
            break;

      case 'W':
            water(2000);
            break;


      case 'E':

            int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
            //Serial.println(reading); // send the received data back to raspberry pi
            break;

//it never enters any of these cases below

      case 'M':

        //String reading2 = moist_sensor.packaged_reading();
        //Serial.println(reading2); // send the received data back to raspberry pi
        break;
        

      case 'W':
        
        water(5000);
        break;

      default:

        delay(5000);

    }
  }


I’ve tried changing the name of the function with fears of special keywords, swapping it with other cases (such as putting case ‘W’ above, where it works, and vice versa), and I always get the same behaviour. If i comment the line, everything works as expected.

I know the method isn’t actually called all the time, but for sanity’s sake, moist_sensor.readd() right now is just:

int readd() {
return 0; 
}

It also works fine if its the last case, but this buggs me, and I want to create other cases with function calls.

Thank you so much!

Понравилась статья? Поделить с друзьями:
  • Error jump to case label default
  • Error jubyphonic перевод
  • Error jtag scan chain interrogation failed all ones
  • Error json parse error undefined
  • Error json decode stream url