Say I have a switch statement with five cases, but only two real methods ever being called, like so:
switch (condition) {
case conditionOutcome1:
[self firstMethod];
break;
case conditionOutcome2:
[self secondMethod];
break;
case conditionOutcome3:
[self firstMethod];
break;
case conditionOutcome4:
[self firstMethod];
break;
case conditionOutcome5:
[self secondMethod];
break;
default:
break;
}
Is it safe to group up the cases, like so?
switch (condition) {
case conditionOutcome1:
case conditionOutcome3:
case conditionOutcome4:
[self firstMethod];
break;
case conditionOutcome2:
case conditionOutcome5:
[self secondMethod];
break;
default:
break;
}
It works fine, but I've never used it before in objective-c so I'd like to make sure I'm not causing any problems by saving a few lines of code.
Thanks!
Fall through is a type of error that occurs in various programming languages like C, C++, Java, Dart …etc. It occurs in switch-case statements where when we forget to add a break statement and in that case flow of control jumps to the next line.
The expression used in a switch statement must have an integral or enumerated type or be of a class type in which the class has a single conversion function to an integral or enumerated type. You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
If you want your switch statement fall through or you want C style fallthrough feature then you can use fallthrough statement. This statement is used to forcefully execute the case present next after the matched statement even though the case is not matching the specified condition.
A fallthrough statement causes program execution to continue from one case in a switch statement to the next case. Program execution continues to the next case even if the patterns of the case label don't match the value of the switch statement's control expression.
Just adding to the other answers, it's called a fallthrough, you can read about it here.
Yes, it's fine to do that.
I've used it before. It stops duplicate code.
Yes 100% safe to use
switch (condition) {
case conditionOutcome1: case conditionOutcome3: case conditionOutcome4: [self firstMethod]; break; case conditionOutcome2: case conditionOutcome5: [self secondMethod]; break; default: break; }
This is always used, for multiple case
s which have same set of actions (duplicate codes) to be performed.
As all the cases
will be performed untill a break
get encountered.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With