Diana
Diana

Reputation: 95

Fall-through if default is in middle of switch case?

I have a question. In a switch statement, is default tested for last even if it isn't last?

If so, in the following code snippet:

int i = 6;
int a=0, b=0, c=0;
switch (i) 
{
    case 1: 
    a++; 
    case 2: 
    default: 
    case 3: 
    b++; 
    case 6:
    c++; 
}
System.out.println(a + " " + b + " " + c); 

After matching with case 6, and incrementing the value of c, since there is no break, will it go back to default?

I did try this code and it didn't seemly go to default and a fall-through did not occur. I just wanted to know?

Upvotes: 3

Views: 2714

Answers (3)

rgettman
rgettman

Reputation: 178333

There is no additional testing of case labels beyond the initial testing at the beginning of the switch statement. Once i has been evaluated by the switch statement, control transfers to the case 6: label because that matches i. Statements are then executed in order until the end of the switch statement, or until a break statement is encountered. This means that only c is incremented.

A break statement will only end the execution of the entire switch statement; whether a break statement is present has no effect on retesting the switch expression, because retesting the switch expression will not occur either way.

If you want default to be the case label entered, then i must not match any case label at the start of the switch statement. If i is 99 at the start of the switch statement, then both b and c are incremented (fallthrough occurs).

There is no restriction on where in the order of case labels a default label appears, only that at most one default occurs in a switch statement.

Upvotes: 2

Ivan
Ivan

Reputation: 8758

switch is evaluated from matching case to either break or end of switch statement. If you pass 6 it will enter case for 6 and do only one increment. But if you enter 7 it will start from default and fall through to the end of switch doing two increments.

Upvotes: 2

DarceVader
DarceVader

Reputation: 98

Currently, all of your cases will fall through, as no case has a break; as well, your switch is conditionally based on i, so if you want to see each case, you need to change i.

Utilizing break; should not have any effect on where your cases reside in your switch state, this is also the "case" for default

Edit: As @Ivan mentioned, if fall through is intended, then the placement of your cases will matter

Upvotes: 1

Related Questions