+ 3

Why do we use break in switch statements??

1st Nov 2016, 5:43 PM
Uplabdhi Singh
Uplabdhi Singh - avatar
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 */
1st Nov 2016, 6:57 PM
Graham Caswell
Graham Caswell - avatar
+ 3
To prevent checking the other cases once a case is matched.
1st Nov 2016, 9:36 PM
Hasan Al-Yazidi
Hasan Al-Yazidi - avatar
+ 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)
2nd Nov 2016, 10:16 AM
Ziyaan Hassan
Ziyaan Hassan - avatar