+ 3
Why do we use break in switch statements??
3 Respuestas
+ 10
break allows the program to come out of the switch statement. Without the break it will return all values after the correct case inside the switch
for example:
int age = 42;
switch (age) {
case 16:
cout << "Too young" << endl;
case 42:
cout << "Adult" << endl;
case 70:
cout << "Senior" << endl;
default:
cout <<"This is the default case" << endl;
}
/* Outputs
Adult
Senior
This is the default case
*/
if you added the breaks it would look like this
int age = 42;
switch (age) {
case 16:
cout << "Too young" << endl;
break;
case 42:
cout << "Adult" << endl;
break;
case 70:
cout << "Senior" << endl;
break;
default:
cout <<"This is the default case" << endl;
}
/* Outputs
Adult
*/
+ 3
To prevent checking the other cases once a case is matched.
+ 1
if you don't use break s it will end up executing all the code below until a break statement comes(or switch statement ends)