Does case-switch work like this?

前端 未结 5 529
广开言路
广开言路 2020-11-30 09:45

I came across a case-switch piece of code today and was a bit surprised to see how it worked. The code was:

switch (blah)
{
case a:
  break;
case b:
  break;         


        
5条回答
  •  暖寄归人
    2020-11-30 10:16

    This is called case fall-through, and is a desirable behavior. It allows you to share code between cases.

    An example of how to use case fall-through behavior:

    switch(blah)
    {
    case a:
      function1();
    case b:
      function2();
    case c:
      function3();
      break;
    default:
      break;
    }
    

    If you enter the switch when blah == a, then you will execute function1(), function2(), and function3().

    If you don't want to have this behavior, you can opt out of it by including break statements.

    switch(blah)
    {
    case a:
      function1();
      break;
    case b:
      function2();
      break;
    case c:
      function3();
      break;
    default:
      break;
    }
    

    The way a switch statement works is that it will (more or less) execute a goto to jump to your case label, and keep running from that point. When the execution hits a break, it leaves the switch block.

提交回复
热议问题