Why do we need break after case statements?

后端 未结 17 2035
猫巷女王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 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.

提交回复
热议问题