Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
201 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...