Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

java - break and switch appears to execute all case statements

In the latest stable release of Java and Eclipse (Kempler), entering the following code and executing it, assuming the package and class names exist:

package some_package;

public class what_the_heck {

    public static void main(String[] args) {
        int p = 2;
        int x = 1;
        switch(p){  
            case (1):
                x--;
            case (2):
                x = 2;
            case (3):
                x = 3;
            default:
                x++;
        }
        System.out.println(x);
    }
}

This prints the value 4. Originally, I thought it should print 2 because I thought that even if there were no break statements, each piece of code is still held in a case statement. Now I think that the issue lies in how it is compiled. For example, my current belief is that internally a boolean keeps track of whether or not a case statement was equal to the value. If it was, then the boolean is true and all case statements will be treated as true until a break is found. This makes sense, but I am still wondering if there are other reasons behind this, or if I am entirely wrong in my assumption.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The reason why switch works as it does is that this:

switch(p){  
        case (1):
            x--;
        case (2):
            x = 2;
        case (3):
            x = 3;
        default:
            x++;
    }

is really just syntactic sugar for this (basically):

if (p == 1)
    goto .L1;
else if (p == 2)
    goto .L2;
else if (p == 3)
    goto .L3;
else
    goto .L4;

.L1:
    x--;
.L2:
    x = 2;
.L3:
    x = 3;
.L4:
    x++;

Java doesn't have a goto statement, but C does, and that's where it comes from. So if p is 2, it jumps to .L2 and executes all the statements following that label.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...