Why Do We Need Break After Case Statements

Why do we need break after case statements?

Sometimes it is helpful to have multiple cases associated with the same code block, such as

case 'A':
case 'B':
case 'C':
doSomething();
break;

case 'D':
case 'E':
doSomethingElse();
break;

etc. Just an example.

In my experience, usually it is bad style to "fall through" and have multiple blocks of code execute for one case, but there may be uses for it in some situations.

Why was the switch statement designed to need a break?

Many answers seem to focus on the ability to fall through as the reason for requiring the break statement.

I believe it was simply a mistake, due largely because when C was designed there was not nearly as much experience with how these constructs would be used.

Peter Van der Linden makes the case in his book "Expert C Programming":

We analyzed the Sun C compiler sources
to see how often the default fall
through was used. The Sun ANSI C
compiler front end has 244 switch
statements, each of which has an
average of seven cases. Fall through
occurs in just 3% of all these cases.

In other words, the normal switch
behavior is wrong 97% of the time.
It's not just in a compiler - on the
contrary, where fall through was used
in this analysis it was often for
situations that occur more frequently
in a compiler than in other software,
for instance, when compiling operators
that can have either one or two
operands:

switch (operator->num_of_operands) {
case 2: process_operand( operator->operand_2);
/* FALLTHRU */

case 1: process_operand( operator->operand_1);
break;
}

Case fall through is so widely
recognized as a defect that there's
even a special comment convention,
shown above, that tells lint "this is
really one of those 3% of cases where
fall through was desired."

I think it was a good idea for C# to require an explicit jump statement at the end of each case block (while still allowing multiple case labels to be stacked - as long as there's only a single block of statements). In C# you can still have one case fall through to another - you just have to make the fall thru explicit by jumping to the next case using a goto.

It's too bad Java didn't take the opportunity to break from the C semantics.

Should we break the default case in switch statement?

Should we use a break; in the last default case?

From The C programming language - Second edition (K&R 2):

Chapter 3.4 Switch

As a matter of good form, put a break after the last case (the default
here) even though it's logically unnecessary. Some day when another
case gets added at the end, this bit of defensive programming will
save you.

Why does switch in Java rely on break?

Sometimes you need multiple cases to execute the same function. For example, I am letting a user specify either mode 1 or mode 32 to represent 32-bit mode, and mode 2 or mode 64 for 64-bit mode.

switch (input) {

case 1:
case 32:
/* Do 32-bit related code */
break;
case 2:
case 64:
/* Do 64-bit related code */
break;
default:
System.out.println("Invalid input");

}

This is why breaks are important. They tell the switch statement when to stop executing code for a given scenario. Additionally, the default is generally used for when the switch does not match ANY case.

Do you need break in switch when return is used?

Yes, you can use return instead of break...

break is optional and is used to prevent "falling" through all the other case statements. So return can be used in a similar fashion, as return ends the function execution.

Also, if all of your case statements are like this:

case 'foo':
$result = find_result(...);
break;

And after the switch statement you just have return $result, using return find_result(...); in each case will make your code much more readable.

Lastly, don't forget to add the default case. If you think your code will never reach the default case then you could use the assert function, because you can never be sure.

switch-case statement without break

The break acts like a goto command. Or, as a better example, it is like when using return in a void function. Since it is at the end, it makes no difference whether it is there or not. Although, I do like to include it.

Using break after default in switch statement when default not at end

As the tutorial states

The default keyword specifies the code to run if there is no case match

The position of the default keyword doesn't matter, the cases after it will be tested before executing the code in the default case. If one of those cases match, its code will be executed, so the break in the default block won't be executed.

The code after default is only executed if none of the explicit cases match, or the case before default is chosen and there's no break before default (so it falls through).

The default: case is usually written last by convention, so a break is not normally needed there. The warning in the tutorial is just a reminder that if you put default: earlier, the rule that you continue into the next case when there's no break still applies; there's nothing special about the default rule that would prevent it.

Why does C++ require breaks in switch statements?

This is for the favour of "falling throught" cases:

switch (x)
{
case 0:
case 1:
std::cout << "x is 0 or 1." << std::endl;
break;
}

In this example, the case statement is executed if x is either 0 or 1.

Should you use break in switch case loops?

When a case condition is met in a switch statement it will execute all of the code blocks within that switch statement until it hits an exit command (think break or return). So the break is not only changing performance speed it's also changes functionality.

An easy way to think about switch statements is as alternative's to chained if-else statements.

your switch code can just as easily be written

if (num % 15 == 0) {
console.log("FizzBuzz");
} else if (num % 3 == 0) {
console.log("Fizz");
} else if (num % 5 == 0) {
console.log("Buzz");
} else {
console.log(num);
}

if you remove the break; statements you'll change how the code actually functions. It will perform more like

if (num % 15 == 0) {
console.log("FizzBuzz");
}

if (num % 3 == 0 || num % 15 == 0) {
console.log("Fizz");
}

if (num % 5 == 0 || num % 3 == 0 || num % 15 == 0) {
console.log("Buzz");
}

console.log(num);

The main difference being the lack of an else condition.



Related Topics



Leave a reply



Submit