catch32
catch32

Reputation: 18612

Strange semantics of switch statement

I met this variations of switch statement, and I wondering to know in witch cases it can be used?

Strangeness is because it doesn't have cases before default value, only after. And doesn't have break statement. But works fine.

Here is code:

public static Item newItem() {
    switch (rand.nextInt(3)) {
    default:
    case 0:
        return new Scissors();
    case 1:
        return new Paper();
    case 2:
        return new Rock();
    }
}

How does it really can be execute at this strange style. I tried to make easy debugging all works fine it return accuracy one explicit instance.

Question: why does we need write:

default:
case 0: 

instead typical usage:

case 0:
default:

Compiler didn't let to change or comment default statement.

Any suggestions?

PS please, don't write silly explanation how does switch works. it's clear. write only about this explicit example.

BTW I met this peace of code at Thinking in Java by Bruce Eckel.

Upvotes: 0

Views: 369

Answers (5)

Bartosz Klimek
Bartosz Klimek

Reputation: 565

The code could be modified for improved readability and a standard look:

switch(...)
{
  case 0:
    ...
  case 1:
    ...
  case 2:
    ...
  default:
    // Not reachable
    throw new RuntimeException("Unexpected value");
}

Default label is necessary since the compiler cannot guess that only 0, 1 and 2 are possible.

Upvotes: -2

Roman C
Roman C

Reputation: 1

The method should return a value, as it declared by the method, so it should have a return statement. If you comment default the method might not return the value. It doesn't matter where you put default but you should do it to satisfy return condition.

Upvotes: 0

Oswald
Oswald

Reputation: 31685

The break is optional. If a case matches and no break is encountered, the following case is executed without being tested. That's why

case 0:
default:
  // Some code here

works as you expect it to.

The default case is special. It is executed if no other case matches. It does not matter where you put it (at the beginning, in the middle or (as is custom) at the end).

In your code, if case 0: matches, case 1: is not executed only because the function never gets that far: a new Scissors() is returned instead.

Upvotes: 0

Mureinik
Mureinik

Reputation: 312219

The default branch just means "the branch for all the options not explicitly specified. It's a convention to put it at the end of the switch-case statement, but is not required.

break is also not required - if a branch of the switch-case does not end with break, it will just continue on executing the code in the next branch - this is called fallthrough. However, here you do not need it because each branch just returns, so the function's execution does not continue.

Upvotes: 3

MillaresRoo
MillaresRoo

Reputation: 3848

Return causes the exit. There's no need to add a break statement.

Upvotes: 1

Related Questions