Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does case-switch work like this?

Tags:

c++

c

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?

like image 422
Manish Avatar asked Nov 16 '11 02:11

Manish


People also ask

How does a switch-case work?

The switch case in Java works like an if-else ladder, i.e., multiple conditions can be checked at once. Switch is provided with an expression that can be a constant or literal expression that can be evaluated. The value of the expression is matched with each test case till a match is found.

How does a switch-case work internally?

The order of the switch statements as such doesn't matter, it will do the same thing whether you have the order in ascending, descending or random order - do what makes most sense with regard to what you want to do. If nothing else, switch is usually a lot easier to read than an if-else sequence.

Are switch cases efficient?

As it turns out, the switch statement is faster in most cases when compared to if-else , but significantly faster only when the number of conditions is large. The primary difference in performance between the two is that the incremental cost of an additional condition is larger for if-else than it is for switch .

Do switch cases work with strings?

Yes, we can use a switch statement with Strings in Java.


1 Answers

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.

like image 65
Merlyn Morgan-Graham Avatar answered Oct 02 '22 19:10

Merlyn Morgan-Graham