+ 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.
8 Answers
+ 2
yes, until x is 20!
+ 2
Ok, thanks for your answers.
+ 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
0
No, it will not print bye until x is 10. Check your code!
0
You mean 20? I will check again.
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).
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!!
0
hi