Why do we need break after case statements?

后端 未结 17 2050
猫巷女王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:52

    I am now working on project where I am in need of break in my switch statement otherwise the code won't work. Bear with me and I will give you a good example of why you need break in your switch statement.

    Imagine you have three states, one that waits for the user to enter a number, the second to calculate it and the third to print the sum.

    In that case you have:

    1. State1 - Wait for user to enter a number
    2. State2 - Print the sum
    3. state3 - Calculate the sum

    Looking at the states, you would want the order of exaction to start on state1, then state3 and finally state2. Otherwise we will only print users input without calculating the sum. Just to clarify it again, we wait for the user to enter a value, then calculate the sum and prints the sum.

    Here is an example code:

    while(1){
        switch(state){
          case state1:
            // Wait for user input code
            state = state3; // Jump to state3
            break;
          case state2:
            //Print the sum code
            state = state3; // Jump to state3;
          case state3:
            // Calculate the sum code
            state = wait; // Jump to state1
            break;
        }
    }
    

    If we don't use break, it will execute in this order, state1, state2 and state3. But using break, we avoid this scenario, and can order in the right procedure which is to begin with state1, then state3 and last but not least state2.

提交回复
热议问题