+ 1

Why does the switch statement automatically execute any code that isn't preceded by a break?

Shouldn't it check if the conditions match first? For example int x = 10 switch(x) case 10 print Hi case 20 print Bye This prints Hi Bye even if the second case isn't met.

4th Sep 2016, 1:08 PM
Kevin Chang
Kevin Chang - avatar
8 Answers
+ 2
yes, until x is 20!
4th Sep 2016, 1:16 PM
Mohit Lamba
Mohit Lamba - avatar
+ 2
Ok, thanks for your answers.
4th Sep 2016, 1:30 PM
Kevin Chang
Kevin Chang - avatar
+ 1
Sorry but this aint switch statement In a situation when a case ( say case 1 )is found , the corresponding statements of case 1are executed if a break is encountered overthere in case 1 block , the control immediately passes on to the line of code after the whole block of switch statement without going thru other cases if a break isnt encountered , the control passes to next case clause here only if case ( case 2 ) matches , the statements of case 2 are executed otherwise not and the process goes on until a break statement or the end of switch block is encountered
4th Sep 2016, 3:06 PM
Harsh
0
No, it will not print bye until x is 10. Check your code!
4th Sep 2016, 1:11 PM
Mohit Lamba
Mohit Lamba - avatar
0
You mean 20? I will check again.
4th Sep 2016, 1:13 PM
Kevin Chang
Kevin Chang - avatar
0
The code playground executed any statement after matching the first one if there wasn't a break. For example day = 1 switch (day) case 1 print Monday case 2 print Tuesday break; case 3 Wednesday prints out Monday Tuesday (the code is written in shorthand of course).
4th Sep 2016, 1:18 PM
Kevin Chang
Kevin Chang - avatar
0
Well, then I fear there must be a problem because switch doesn't work that way. break is used to save execution time for checking every case if the condition is already met. Try running your code in PC!!
4th Sep 2016, 1:26 PM
Mohit Lamba
Mohit Lamba - avatar
0
hi
19th Sep 2016, 11:00 AM
Đông Phấm
Đông Phấm - avatar