简体   繁体   中英

What is the meaning of this Java code?

It happened to me recently to write a piece of code similar to this one:

switch (x) {
    case a: case b: case c:
    // do something
    break;
    case d: case e: case f:
    // do something
    break;
}

Then, I got wrong and wrote a similar code with a syntax error: I forgot to write the case keyword:

switch (x) {
    case a: b: c:
    // do something
    break;
    case d: e: f:
    // do something
    break;
}

This syntax is actually valid in some other languages and the switch passes through all the values.

Actually here is valid too, as I did not get any syntax error: but a wrong behaviour by the program that was executing the switch smoothly, only missing the values without the case keyword.

Why? What does the b; c:, e: and f: mean in the second snip?

Are they maybe labels ? And then, how could they possibly be on the same line? What am I missing that I don't understand behind this weird non-error?

Edit: they appear to be indeed labels . It's unusual and as @Bathsheba explained, the problem is that labels are generally at the begin of a line. Weird how Java allows such a confusing (in my mind) syntax, without even showing a warning. This can create really a lot of confusion and weird errors in long programs.

Thank you.

In the second case, b: , c: , e: , and f: are labels . You are allowed to break to a label in Java, and the language allows you to insert a label in all sorts of places, including the places where you have.

It's just unusual to see labels not starting at the beginning of a line, that's all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM