Turn off the operator, make the previously set switching case by default?

I would like to do something like this:

int i = 0;

switch(difficulty) {
    case 1: i++; break;
    case 2: i--; break;
    default: case 1;
}   

      

Is something like this possible? I want to prevent code duplication. I know there is no reason for this in this particular example, since the duplicated code would be small. The only thing I can think of is something like this [using toggle on toggle capabilities]:

switch(difficulty) {
    case 2: i--; break;
    default:
    case 1: i++; break;
}   

      

I would prefer not to do it this way, because it would make more sense to increase the number of numbers and have a default at the bottom.

But I wonder if I did that, would it mess up the goto statements under the hood? In particular, doesn't it take longer to decide which goto to use with numbers or out of order? Does the order in a switch statement matter? Imagine all cases have the same chance of being named, would it matter if you had them in random order instead of linear order?

[Edit: For my performance question, I found this: Does the order of the switch statements matter, the short answer is no: Does the sort order matter to speed? How does Java switch work under the hood?

+3


source to share


5 answers


This is probably what you want / want and is valid code



int i = 0;      
    switch (difficulty) {
    default:
    case 1: i++; break;
    case 2: i--; break;
    }

      

+4


source


This should suit your needs:



switch(difficulty) {
    case 2: i--; break;
    default: i++; break;
}

      

+10


source


As far as I know, the order of affairs does not change the switch statement in any way, either your parameter is appropriate for the case or not, so in your case it doesn't matter, case you are the first. You can check the documentation if you like. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

+2


source


(moved on from comment as it was helpful)

Add a private method and call it both from case 1

and default

, this way you won't have duplicate code.

+1


source


No, in a switch statement it doesn't matter. Also, the compiler always maintains a hash table to go to a switch statement. Thus, casing ordering or enlargement is not at all an issue. This is always an O (1) operation. However, this will reduce the switching for your case:

switch(difficulty) {
    case 2: i--; break;
    default: i++; break;
}

      

0


source







All Articles