+ 1

I have a problem with c++, can someone help me?

I'm an informatic student and at my school we started learning c++. I'm really into but when i was doing one of my homework for the switch case i run in to a problem. When i run my code at a default case codeblocks tell me this: "error: jump to case label [-fpermessive], but i don't know how to resolve it, even though I don't really know what that means... I would be grateful if someone could explain me how to solve. But remember that my programming level is not that high since I have just started learning. I copy the code below, know that there are about 100 lines and that both above and below this part there is much more. Thanks to all. do { cin >> condizione; switch (condizione) { case 'P': cout << "Hai selezionato lo sconto dedicato ai pensionati. Ricevi uno sconto sul prezzo del 10%." << endl; sconto=10; break; case 'S': cout << "Hai selezionato lo sconto dedicato agli studenti. Ricevi uno sconto sul prezzo del 15%." << endl; sconto=15; break; case 'D': cout << "Hai selezionato lo sconto dedicato ai disoccupati. Ricevi uno sconto sul prezzo del 25%." << endl; sconto=25; break; case 'N': cout << "Non hai selezionato uno sconto." << endl; bool scontato=false; break; default: cout << "Seleziona un'opzione esistente." << endl; break; } }while(condizione!='P' && condizione!='S' && condizione!='D' && condizione!='N');

2nd Jun 2021, 12:41 PM
Psico
Psico - avatar
4 Antworten
+ 5
Why is the boolean variable <scontato> defined inside of the 'N' case? was that intentional?
2nd Jun 2021, 1:23 PM
Ipang
+ 2
Your code looks fine .. (but have warnings) Psico Try it just retype default case again...
2nd Jun 2021, 1:12 PM
Jayakrishna 🇮🇳
+ 2
Hey friend , When i run your code i got 1 error and 1 warning Error: jump to case label 29 | default: | ^~~~~~~ Warning: crosses initialization of 'bool scontato' 26 | bool scontato=false; | ^~~~~~~~ The cases in the switch are considered as a "jump". Just put all objects and variables initializations before your switch, and everything will be fine. Consider this code: switch(k) { case 1: int t = 4; break; default: break; } It will cause a "crosses initialization" error, because it is possible to skip the initialization of t, but after that it will still be in scope, even though it was never created in the first place. Now consider this: switch(k) { case 1: { int t = 4; } break; default: break; } Here, you will not have the error, because the variable is inside a block, and will die at the end of the block ( at the closing { ), so after that it will not be in scope in any case. To fix the first case, you just need to do: int t = 0; switch(k) { case 1: t = 4; break; default: break; }
2nd Jun 2021, 4:25 PM
saurabh
saurabh - avatar
+ 1
Thanks to all of you guys, i resolved my problem and now all works fine
3rd Jun 2021, 2:02 PM
Psico
Psico - avatar