nus-cs2113-AY2324S2 / forum

2 stars 0 forks source link

Switch format #11

Closed adamzzq closed 7 months ago

adamzzq commented 7 months ago

Hi prof, may I ask for a method that involves a switch like this, is there a need to add a break; at the end of each case? Because when I add a break after a return, the IDE warns me that the break line is an unreachable statement.

MyClass foo(int case) {
    switch (case) {
    case 0:
        return A;
        // break; ?
    case 1:
        return B;
        // break; ?
    case 2:
        return C;
        // break; ?
    default:
        return D;
        // break; ?
    }
}
JackieNeoCEG commented 7 months ago

I think using return itself is sufficient for this case as it immediately exits foo. Any other lines after return will be unreachable, including break.

wenenhoe commented 7 months ago

Yes, I agree with @JackieNeoCEG. Just to add on, using break statements in place of return statements would be necessary if you have additional code after the switch statement and need to run it. But in this case, it is not necessary (and unreachable due to aforementioned reason by @JackieNeoCEG ).

adamzzq commented 7 months ago

Thanks, my friends