I don’t understand where 6 came from, I thought it would be 2, that's why I’m filling up the interviews. I wonder why there are 6, not 2?
|
2 answers
Your arguments forget that there is no break , and in this case the case “fails”. That is, roughly speaking, the compiler sees this code differently, somewhere like that
i = 0; s = 0; s+=2; i+=s; s+=2; i+=s; The correct answer to this question would be - there is no break , this is bad code.
- 7If there is no
breakit doesn’t mean that the code is bad) There are situations when it is intentionally lowered, so that it will fail further - Alexey Shimansky - oneYes, there are tricks when it is lowered. And one of such cases is when there are several cases in a row. And this is normal (just in java6 there is no possibility in the case of writing a range). But the similar code in the example is an example of bad code. - KoVadim
- @KoVadim the correct answer is "6", and not "this is a bad code" :-) - cache
- oneI was asked a similar question at the interview. I asked - do you write all the code like that? Then it was fun. - KoVadim
|
Because after the first case there is no break statement (or another interrupt statement), respectively, the program execution proceeds to the next case .
|

break;- Alexey Shimanskycase 1:whensalready2. It would be clearer if theswichoperator would be replaced with somegoto- go to the label and further code execution after the label. In fact, because it is so. - Igor Kudryashov