In fact, with the C language and Java,oc is also a switch multi-branch statements, can also be called switch statements. The syntax is also very similar. Let's take a slow look at switch.
(a) Code one:
int main (int argc, const char * argv[]) { @autoreleasepool { int i=6; switch (i) {case 1: NSLog (@ "Monday"); break; Case 2: NSLog (@ "Tuesday"); break; Case 3: NSLog (@ "Wednesday"); break; Case 4: NSLog (@ "Thursday"); break; Case 5: NSLog (@ "Friday"); break; Case 6: NSLog (@ "Saturday"); break; Case 7: NSLog (@ "Week seven"); break; } } return 0;}
Output Result:
。
Results analysis: In fact, the switch statement can be fully used if-else if statements to achieve, but the code will appear to be more redundant, not so cool. So you need to use switch. The switch statement is to make a variable match, and to match the case statement below, execute the statement under that case. If you encounter a break, exit the entire switch, or you will continue to execute.
(b) Code two:
int main (int argc, const char * argv[]) { @autoreleasepool { int i=3; switch (i) {case 1: NSLog (@ "Monday"); Case 2: NSLog (@ "Tuesday"); Case 3: NSLog (@ "Wednesday"); Case 4: NSLog (@ "Thursday"); Case 5: NSLog (@ "Friday"); Case 6: NSLog (@ "Saturday"); Case 7: NSLog (@ "Week seven"); } } return 0;}
Output Result:
。
Result Analysis: If there is no break statement in switch, when case matches to a value, the switch will not exit immediately, but will proceed sequentially to execute the statements under all of the following cases.
(c) Code three:
int main (int argc, const char * argv[]) { @autoreleasepool { int i=9; switch (i) {case 1: NSLog (@ "Monday"); break; Case 2: NSLog (@ "Tuesday"); break; Case 3: NSLog (@ "Wednesday"); break; Case 4: NSLog (@ "Thursday"); break; Case 5: NSLog (@ "Friday"); break; Case 6: NSLog (@ "Saturday"); break; Case 7: NSLog (@ "Week seven"); break; Default: NSLog (@ "error occurred"); break; } } return 0;}
Output Result:
。
Result Analysis: If a variable does not match anything in the case, it will eventually match the default. Outputs the contents of default.
In summary, the individual feels that the disadvantage of the switch statement is that it is not possible to make conditional judgments behind the case, which is different from if-else if. Can only be a specific value and cannot be a range.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
OBJECTIVE-C Study Notes (12)--switch use of multi-branch statements