Break doesn't work in swith stmt

Sorry about the Italian, but i don't have time to translate. The program works perfectly, the question is why doesn't break work? You know, my professor doesn't want us to use goto, and if i replace it with break; it basically doesn't exit the switch stmt. Can you guys help me out?

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
#include <iostream>
using namespace std;
int main()
{
int x;
bool b;
float p,c,r1,r2,y=2.54;
stop:
	do
	{
		cout<<"Scegli un'operazione:\n1. Conversione pollici --> cm\n2. Conversione cm --> pollici\n3. Termina"<<endl;
		cin>>x;
		switch(x)
		{
	
			case(1):
				do
				{
				
 					cout<<"Inserisci il numero di pollici da convertire"<<endl;
					cin>>p;
	   						if(p<0 || cin.fail())
							{
								cout<<"Input non valido - ripeti"<<endl;
								cin.clear();
								cin.ignore(256, '\n');
								b=true;
							}
						else
						{
							r1=p*y;
	 						cout<<"Numero di centimetri:"<<r1<<endl;
	 						b=false;
	 						goto stop;
	 				        }
				}
				while(b);	
	    	case(2):
	    			do
	    			{
						cout<<"Inserisci il numero di cm da convertire"<<endl;
	   					cin>>c;
	   						if(c<0 || cin.fail())
							{
								cout<<"Input non valido - ripeti"<<endl;
								cin.clear();
								cin.ignore(256, '\n');
								b=true;
							}
							else
							{
	    						     r2=c/y;
	    						     cout<<"Numero di pollici:"<<r2<<endl;
	    						     b=false;
	    						     goto stop;
	    					        }
	    			}
	    			while(b);
	 		case(3):
	 				cout<<"Grazie e arrivederci!"<<endl;
	 				return 0;
	 		default:
	 				cin.clear();
	 				cin.ignore(256, '\n');
	 				cout<<"Scelta non valida - ripeti"<<endl;
		}
	}
while(true);
}
 
Last edited on
break applies to the deepest structure applicable at the point of usage. So if you're in a loop that's inside a switch, you'll break out of the loop but stay in the switch. If you're in a switch that's inside a loop you'll break out of the switch and stay in the loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
while (true){
    std::cout << "Inside outer loop.\n";
    int a = 0;
    switch (a){
        case 0:
            while (true){
                std::cout << "Inside inner loop: " << a << std::endl;
                if (a > 4)
                    break;
                a++;
            }
            std::cout << "Outside the loop, inside the switch.\n";
            break;
    }
}
Output:
Inside outer loop.
Inside inner loop: 0
Inside inner loop: 1
Inside inner loop: 2
Inside inner loop: 3
Inside inner loop: 4
Outside the loop, inside the switch.
Inside outer loop.
Inside inner loop: 0
Inside inner loop: 1
Inside inner loop: 2
(etc.)
Thanks i managed to fix it putting break; inside each case():
Last edited on
@BlueRyse

Here are some ideas to consider about your code:

* Each case in the switch should call a function, that function should return a value
* Provide a Quit case in the switch. Make it operate on a bool variable:

1
2
3
4
5
6
7
8
9
10
bool Quit = false;

while (!Quit) {
  // switch
   // other cases
  case 3:
      Quit = true;
      std::cout << "Grazie e arrivederci!\n";
      break;
}



That way you could avoid the infinite loops, the do loops, and the goto. It will also make the code easier to read. The return 0; is a bit drastic - it ends the program, this way you can provide a sane end to the loop. You could also do away with the do {} while(b); in each case.

Try to avoid using goto, unless you know what you are doing. I am not saying goto should be banned, there are valid uses for it. But it is something beginners should avoid, this is an example where it can be avoided.

Having a break; after each case is normal practise for switch statements, unless one wants it to fall through each case on purpose.

You could also have a function for validation: Lines 22 to 28 and 43 to 49 are very similar. If you find yourself writing the same code over and over, then write a function.

Prefer double over float, the latter precision is easily exceeded.

With the variables, choose meaningful names, don't abbreviate everything to a single char identifier. Ideally wait until you have a sensible value to assign, then do declaration and assignment all on 1 line. Do 1 variable per line.

Variables like y should be const:

const double y InchesToCm - 2.54;

Finally, try to avoid using namespace std; There is lots written about this - Google / wiki it :+)
Registered users can post here. Sign in or register to post.