Why do we need break after case statements?

后端 未结 17 2027
猫巷女王i
猫巷女王i 2020-11-22 04:34

Why doesn\'t the compiler automatically put break statements after each code block in the switch? Is it for historical reasons? When would you want multiple code blocks to e

相关标签:
17条回答
  • 2020-11-22 04:57

    because there are situations where you want to flow through the first block for example to avoid writing the same code in multiple blocks but still be able to divide them for mroe control. There are also a ton of other reasons.

    0 讨论(0)
  • 2020-11-22 05:00

    It is an old question but actually I ran into using the case without break statement today. Not using break is actually very useful when you need to combine different functions in sequence.

    e.g. using http response codes to authenticate user with time token

    server response code 401 - token is outdated -> regenerate token and log user in.
    server response code 200 - token is OK -> log user in.

    in case statements:

    case 404:
    case 500:
            {
                Log.v("Server responses","Unable to respond due to server error");
                break;
            }
            case 401:
            {
                 //regenerate token
            }
            case 200:
            {
                // log in user
                break;
            }
    

    Using this you do not need to call log in user function for 401 response because when the token is regenerated, the runtime jumps into the case 200.

    0 讨论(0)
  • 2020-11-22 05:01

    Sometimes it is helpful to have multiple cases associated with the same code block, such as

    case 'A':
    case 'B':
    case 'C':
        doSomething();
        break;
    
    case 'D':
    case 'E':
        doSomethingElse();
        break;
    

    etc. Just an example.

    In my experience, usually it is bad style to "fall through" and have multiple blocks of code execute for one case, but there may be uses for it in some situations.

    0 讨论(0)
  • 2020-11-22 05:04

    Java is derived from C, whose heritage includes a technique known as Duff's Device . It's an optimization that relies on the fact that control falls through from one case to the next, in the absence of a break; statement. By the time C was standardized, there was plenty of code like that "in the wild", and it would have been counterproductive to change the language to break such constructions.

    0 讨论(0)
  • 2020-11-22 05:05

    Not having an automatic break added by the compiler makes it possible to use a switch/case to test for conditions like 1 <= a <= 3 by removing the break statement from 1 and 2.

    switch(a) {
      case 1: //I'm between 1 and 3
      case 2: //I'm between 1 and 3
      case 3: //I'm between 1 and 3
              break;
    }
    
    0 讨论(0)
提交回复
热议问题