Ошибка 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 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);
  }

Offline

Зарегистрирован: 30.03.2015

Здравствуйте господа! Сразу скажу — я только учусь. Нашел на просторах скетч (здесь уже с моими вставками!)

    // https://youtu.be/_hnk5jNTudk Low power NeoPixel goggles example. Makes a nice blinky display
    // with just a few LEDs on at any time.
     
    #include <Adafruit_NeoPixel.h>
        
    #define PIN 1
     
    Adafruit_NeoPixel pixels = Adafruit_NeoPixel(48, PIN);
     
    uint8_t mode = 0, // Эффект по умолчанию
    offset = 0; // Position of spinny eyes
    uint32_t color = 0xFF0000; // Start red
    uint32_t prevTime;
    //Путь пикселей при змейке - 48 всего
    int sine[] = {20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0,23,22,21,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,24,25,26,27};
    int sine2[] = {20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0,23,22,21,27,26,25,24,47,46,46,44,43,42,41,40,39,38,37,36,35,34,33,32,31,30,29,28};

    void setup() {
    pixels.begin();
    pixels.setBrightness(120); // Пол яркости
    prevTime = millis();
    }
     
    void loop() {
    uint8_t i;
    uint32_t t;
     
    switch(mode) {
     
    case 0: // Хаотичные блики - вспышки разных диодов в разное время!
      i = random(48);
      pixels.setPixelColor(i, color);
      pixels.show();
      delay(10);
      pixels.setPixelColor(i, 0);
      break;
    case 1: // Spinny wheels (8 LED одновременно)
      for(i=0; i<24; i++) {
      uint32_t c = 0;
      if(((offset + i) & 7) < 2) c = color; // 4 pixels on...
      pixels.setPixelColor( i, c); // Первое очко
      pixels.setPixelColor(47-i, c); // Второе очко (инверсия)
      }
      pixels.show();
      offset++;
      delay(50);
      break;
     case 2: //Змейка
       int r = random(255);
       int g = random(255);
       int b = random(255);
       for(int i=0; i<48; i++) {
        pixels.setPixelColor(sine[i], pixels.Color(0, 0, 0));
          for (int j=0; j<8; j++){
            pixels.setPixelColor(sine[(j+i+1)%48], pixels.Color(r, g, b)); //random RGB color value
          }
        pixels.show();
        delay(80);
      }
      break;
  }
     
    t = millis();
    if((t - prevTime) > 8000) { // Каждые< 8 seconds...
    mode++; // Следующий уровень
    if(mode > 2) { // Последний уровень?
    mode = 0; // Уровни сначала
    color >>= 8; // Следующий цвет R->G->B
    if(!color) color = 0xFF0000; // Сброс на красный
    }
    for(i=0; i<48; i++) pixels.setPixelColor(i, 0);
    prevTime = t;
    }
}

// Input a value 0 to 255 to get a color value.
// The colours are a transition r - g - b - back to r.
uint32_t Wheel(byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if(WheelPos < 85) {
   return pixels.Color(255 - WheelPos * 3, 0, WheelPos * 3);
  } else if(WheelPos < 170) {
    WheelPos -= 85;
   return pixels.Color(0, WheelPos * 3, 255 - WheelPos * 3);
  } else {
   WheelPos -= 170;
   return pixels.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
  }
}

для двух Adafruit WS2812b колец. Скетч запускается и работает. Решил добавить еще один эффект Змейка2. Добавил sine2, изменил «if(mode > 3) { // Последний уровень?» и написал еще один case 3: //Змейка2

case 3: //Змейка2
       int r = random(255);
       int g = random(255);
       int b = random(255);
       for(int i=0; i<48; i++) {
        pixels.setPixelColor(sine2[i], pixels.Color(0, 0, 0));
          for (int j=0; j<8; j++){
            pixels.setPixelColor(sine2[(j+i+1)%48], pixels.Color(r, g, b)); //random RGB color value
          }
        pixels.show();
        delay(80);
      }
      break;

 Но не хочет работать. Пишет огромное количество букв! 

C:DocumentsArduinoMad_scientist_gogglesMad_scientist_goggles.ino: In function 'void loop()':

Mad_scientist_goggles:61: error: jump to case label [-fpermissive]

       case 3: // Zmeyka2

            ^

Mad_scientist_goggles:51: error: crosses initialization of 'int b'

        int b = random(255);

            ^

Mad_scientist_goggles:50: error: crosses initialization of 'int g'

        int g = random(255);

            ^

Mad_scientist_goggles:49: error: crosses initialization of 'int r'

        int r = random(255);

            ^

Mad_scientist_goggles:62: error: redeclaration of 'int r'

        int r = random(255);

            ^

Mad_scientist_goggles:49: error: 'int r' previously declared here

        int r = random(255);

            ^

Mad_scientist_goggles:63: error: redeclaration of 'int g'

        int g = random(255);

            ^

Mad_scientist_goggles:50: error: 'int g' previously declared here

        int g = random(255);

            ^

Mad_scientist_goggles:64: error: redeclaration of 'int b'

        int b = random(255);

            ^

Mad_scientist_goggles:51: error: 'int b' previously declared here

        int b = random(255);

            ^

exit status 1
jump to case label [-fpermissive]

и останавливается при проверке. Помогите пожалуйста вставить этот case в код!

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!
}
click below button to copy the code. By c++ tutorial team
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
}
click below button to copy the code. By c++ tutorial team
switch(choice)
{
    case 1: {
       // .......
    }break;
    case 2: {
       // .......
    }break;
    case 3: {
       // .......
    }break;
}    
click below button to copy the code. By c++ tutorial team

Arduino Forum

Loading

Punk_Joker

1 / 1 / 1

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

Сообщений: 59

1

01.05.2015, 02:12. Показов 7664. Ответов 4

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


Студворк — интернет-сервис помощи студентам

Проблема в фунциии prim начиная с ветки case NAME. Пишу в CodeBlocks+MinGW.

Кликните здесь для просмотра всего текста

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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
#include <iostream>
#include <string>
#include <map>
#include <cctype>
 
using namespace std;
 
enum Token_value
{
    NAME,      NUMBER,     END,
    PLUS='+',  MINUS='-',  MUL='*', DIV='/',
    PRINT=';', ASSIGN='=', LP='(',  RP=')'
};
 
Token_value curr_tok=PRINT;
double number_value;
string string_value;
map<string, double> table;
int no_of_errors;
 
//сложение и вычитание
double expr(bool get);
double term(bool get);
double prim(bool get);
Token_value get_token();
double error(const string& s);
 
double expr(bool get)
{
    double left=term(get);
 
    for ( ; ; )
        switch(curr_tok)
        {
            case PLUS:
                left+=term(true);
                break;
            case MINUS:
                left-=term(get);
                break;
            default:
                return left;
        }
}
 
//умноржение и деление
double term(bool get)
{
    double left=prim(get);
 
    for ( ; ; )
        switch(curr_tok)
        {
            case MUL:
                left*=prim(get);
                break;
            case DIV:
                if (double d = prim(true))
                {
                    left/=d;
                    break;
                }
                return error("devide by 0");
            default:
                return left;
        }
}
 
double prim(bool get)
{
    if (get) get_token();
    switch(curr_tok)
    {
        case NUMBER:
            double v = number_value;
            get_token();
            return v;
        case NAME:
            double& v=table[string_value];
            if (get_token() == ASSIGN) v=expr(true);
            return v;
        case MINUS:
            return -prim(true);
        case LP:
            double e=expr(true);
            if (curr_tok != RP) return error("')' expected");
            get_token();
            return e;
        default:
            return error("primary expected");
    }
}
 
Token_value get_token()
{
    char ch = 0;
    cin>>ch;
    switch(ch)
    {
        case 0:
            return curr_tok=END;
        case ';':
        case '*':
        case '/':
        case '+':
        case '-':
        case '(':
        case ')':
        case '=':
            return curr_tok=Token_value(ch);
        case '0':
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
        case '8':
        case '9':
        case '.':
            cin.putback(ch);
            cin>>number_value;
            return curr_tok=NUMBER;
        default:
            if (isalpha(ch))
            {
                cin.putback(ch);
                cin>>string_value;
                return curr_tok=NAME;
            }
            error("bad token");
            return curr_tok=PRINT;
    }
}
 
double error(const string& s)
{
    no_of_errors++;
    cerr<<"error: " << s <<'n';
    return 1;
}
 
 
 
int main()
{
    table["pi"]=3.1415926535897932385;
    table["e"]=2.7182818284590452354;
    while(cin)
    {
        get_token();
        if (curr_tok==END) break;
        if (curr_tok==PRINT) continue;
        count << expr(false) << 'n';
    }
    return no_of_errors;
}

Лог компиляции

Кликните здесь для просмотра всего текста

||=== Build: Debug in Hello (compiler: GNU GCC Compiler) ===|
D:WorkspaceC++Hellomain.cpp||In function ‘double prim(bool)’:|
D:WorkspaceC++Hellomain.cpp|78|error: jump to case label [-fpermissive]|
D:WorkspaceC++Hellomain.cpp|75|error: crosses initialization of ‘double v’|
D:WorkspaceC++Hellomain.cpp|79|error: conflicting declaration ‘double& v’|
D:WorkspaceC++Hellomain.cpp|75|error: ‘v’ has a previous declaration as ‘double v’|
D:WorkspaceC++Hellomain.cpp|82|error: jump to case label [-fpermissive]|
D:WorkspaceC++Hellomain.cpp|75|error: crosses initialization of ‘double v’|
D:WorkspaceC++Hellomain.cpp|84|error: jump to case label [-fpermissive]|
D:WorkspaceC++Hellomain.cpp|75|error: crosses initialization of ‘double v’|
D:WorkspaceC++Hellomain.cpp|89|error: jump to case label [-fpermissive]|
D:WorkspaceC++Hellomain.cpp|85|error: crosses initialization of ‘double e’|
D:WorkspaceC++Hellomain.cpp|75|error: crosses initialization of ‘double v’|
D:WorkspaceC++Hellomain.cpp|72|warning: enumeration value ‘NAME’ not handled in switch [-Wswitch]|
D:WorkspaceC++Hellomain.cpp|72|warning: enumeration value ‘END’ not handled in switch [-Wswitch]|
D:WorkspaceC++Hellomain.cpp|72|warning: enumeration value ‘PLUS’ not handled in switch [-Wswitch]|
D:WorkspaceC++Hellomain.cpp|72|warning: enumeration value ‘MINUS’ not handled in switch [-Wswitch]|
D:WorkspaceC++Hellomain.cpp|72|warning: enumeration value ‘MUL’ not handled in switch [-Wswitch]|
D:WorkspaceC++Hellomain.cpp|72|warning: enumeration value ‘DIV’ not handled in switch [-Wswitch]|
D:WorkspaceC++Hellomain.cpp|72|warning: enumeration value ‘PRINT’ not handled in switch [-Wswitch]|
D:WorkspaceC++Hellomain.cpp|72|warning: enumeration value ‘ASSIGN’ not handled in switch [-Wswitch]|
D:WorkspaceC++Hellomain.cpp|72|warning: enumeration value ‘LP’ not handled in switch [-Wswitch]|
D:WorkspaceC++Hellomain.cpp|72|warning: enumeration value ‘RP’ not handled in switch [-Wswitch]|
D:WorkspaceC++Hellomain.cpp||In function ‘int main()’:|
D:WorkspaceC++Hellomain.cpp|155|error: ‘count’ was not declared in this scope|
D:WorkspaceC++Hellomain.cpp||In function ‘double prim(bool)’:|
D:WorkspaceC++Hellomain.cpp|92|warning: control reaches end of non-void function [-Wreturn-type]|
||=== Build failed: 12 error(s), 11 warning(s) (0 minute(s), 0 second(s)) ===|



0



Tulosba

:)

Эксперт С++

4773 / 3267 / 497

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

Сообщений: 9,046

01.05.2015, 09:27

2

Нужно добавить фигурные скобки внутрь case’ов:

C++
1
2
3
4
case NUMBER: {
   double v = number_value;
   get_token();
   return v; }

и т.д.



0



0 / 0 / 1

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

Сообщений: 16

02.06.2017, 18:16

3

Обьясни в чем дело, к чему эти скобки в кейсах? Я столкнулся с такой же ошибкой.



0



DrOffset

17460 / 9287 / 2269

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

Сообщений: 16,264

02.06.2017, 18:40

4

Цитата
Сообщение от Сашка Бородач
Посмотреть сообщение

Обьясни в чем дело, к чему эти скобки в кейсах?

Объясняю «на пальцах»: switch — работает как goto, и каждая из меток case не вносит своей собственной области видимости, т.е. все, что ты объявляешь внутри switch, будет сквозняком видно в нижестоящих case`ах. Из-за этого, если мы не сделаем сами область видимости посредством {}, то мы вынуждены будем перепрыгивать через инициализацию, получая обращение к невалидному объекту. Поэтому компилятор такое запрещает. Вот это же на примере:

C++
1
2
3
4
5
6
7
8
9
10
switch(val)
{
case ONE:
    double c = someFunc();
    break;
case TWO:
    // здесь нам будет видна с, но инициализации ее не было.
    // если для простых типов это в меньшей степени страшно, то для классов это может закончиться плачевно - падением программы
    // поэтому лучший вариант - не допускать такого вообще и сразу выдавать ошибку.
}



0



TheCalligrapher

Вездепух

Эксперт CЭксперт С++

10982 / 5965 / 1630

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

Сообщений: 14,962

02.06.2017, 18:46

5

Цитата
Сообщение от Сашка Бородач
Посмотреть сообщение

Обьясни в чем дело, к чему эти скобки в кейсах? Я столкнулся с такой же ошибкой.

В языке С++ запрещается «прыгать» в область видимости локальной переменной в обход ее объявления с инициализатором

C++
1
2
3
goto label;
int x = 42;
label:;       // Ошибка - метка позволяет обойти инициализацию переменной x

А делается ли такой «прыжок» через goto или switch/case — уже не важно.



0



  • Ошибка jsonexception value at activity of type org json jsonarray cannot be converted to jsonobject
  • Ошибка json что это
  • Ошибка json не определено
  • Ошибка json parse error
  • Ошибка jrpcexception asn 1 decode error offset 0 unexpected end of buffer encountered перевод