Does case-switch work like this?

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;
case c:
case d:
case e: 
  {
    /* code here */
  }
  break;
default :
  return;
}

To my surprise in the scenario where the variable was c, the path went inside the "code here" segment. I agree there is no break at the end of the c part of the case switch, but I would have imagined it to go through default instead. When you land at a case blah: line, doesn't it check if your current value matches the particular case and only then let you in the specific segment? Otherwise what's the point of having a case?


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.


That is the correct behavior, and it is referred to as "falling through". This lets you have multiple cases handled by the same code. In advanced situations, you may want to perform some code in one case, then fall through to another case.

Contrived example:

switch(command)
{
   case CMD_SAVEAS:
   {
      this->PromptForFilename();
   } // DO NOT BREAK, we still want to save
   case CMD_SAVE:
   {
      this->Save();
   } break;


   case CMD_CLOSE:
   {
      this->Close();
   } break;

   default:
      break;
}