+ 12
What happens if we don't use break in switch case
12 Réponses
+ 11
Break will return control out of switch case.so if we don't use it then next case statements will be executed until break appears.
+ 7
// A example, lets say you wanna switch x whitch is 1
// x = 1 so the output will be 'Hi', as you can see there is no break
// after the first case so you will first print out 'Hi' and then
// print out the rest too.
int x = 1;
switch (x) {
case 1:
System.out.println("Hi");
case 2:
System.out.println("Hello");
default:
System.out.println("no such number");
}
// This code has no break so the output is:
// Hi
// Hello
// no such number
// But if you use the break at the first case, only the case 1 which is 'Hi'
// will be printed and the rest ignored
// And if you only use break at the first case and change the x variable to 2 which is 'Hello'
// then the output will be:
// Hello
// no such number
+ 7
If there are no breaks then a switch statement falls through its cases. Here are examples in C with and without breaks that given a radius or width 0-20 prints either a circle or a square, prints sequential circles, generates sequential squares, generates a rectangle or sequential rectangles:
https://code.sololearn.com/cmCz5WeRBEXP/?ref=app
https://code.sololearn.com/c2fbbIpkceoE/?ref=app
https://code.sololearn.com/c5Fr90Mr3F05/?ref=app
https://code.sololearn.com/cfsPnMomqwZh/?ref=app
https://code.sololearn.com/cu0LuNjk4Vgc/?ref=app
https://code.sololearn.com/c4NulBu5B0rK/?ref=app
+ 4
The break statement will stop the process inside the switch. If you forget to put break at the end of a switch case, the process will continue going through the following switch cases.
+ 4
Program flow will fall through to the following cases.
+ 3
All the conditions will be executed if there is no break. "Break" basically breaks the condition in switch after it has been evaluated.
+ 2
If we dont use break then the statement next to the next break statement will be given oit or the default
+ 2
If we not given break it execute within that condtion
+ 1
Depends on the logic
+ 1
To add on to what the others already said, this is called fallthrough. It can be useful in certain situations when you want the same thing to happen for multiple cases.
https://code.sololearn.com/ctoJUt6kuWzX/?ref=app
+ 1
It will continue to read the next script lines available rather than stopping and jumping to the end of the script.
https://code.sololearn.com/wF78d4EZe1HB/?ref=app
0
Then it will continue executing next condition if though it's not correct