From 597ba0b9beee9daaa32477f86af4b2afa24d9c9f Mon Sep 17 00:00:00 2001 From: msabitabrata Date: Sat, 1 Dec 2018 01:23:17 +0530 Subject: [PATCH] Switch case with same code for multiple values (#23073) * Switch case with same code for multiple values Handle switch case when single piece of code runs for multiple values. * removed invalid example numbering introduced in merge conflict resolution --- guide/english/c/switch/index.md | 48 ++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/guide/english/c/switch/index.md b/guide/english/c/switch/index.md index eeebaa07f21..824afe1700e 100644 --- a/guide/english/c/switch/index.md +++ b/guide/english/c/switch/index.md @@ -22,6 +22,11 @@ switch (n) case constant2: // code to be executed if n is equal to constant2; break; + + case constant3: + case constant4: + // code to be executed if n is either equal to constant3 or constant4 + break; . . . @@ -77,6 +82,46 @@ int main() { -> 12.4 -> 32.5 - 12.4 = 20.1 ``` + +## Example + +The below code depicts how to handle switch case when single piece of code runs for multiple values. + +```c +#include + +int main() +{ + for (int i=1; i<=4; i++) { + switch (i) { + case 1: + printf("Hello World 1\n"); + break; + + case 2: + case 3: + printf("Hello World 2 or 3\n"); + break; + + case 4: + printf("Hello World 4\n"); + break; + } + } + + return 0; +} +``` + +## Output +```c +Hello World 1 +Hello World 2 or 3 +Hello World 2 or 3 +Hello World 4 +``` + + ## Nested Switch Case Like nested if, we can use nested switch case in C programming. A switch case statement enclosed inside another switch case statement is called nested switch case. Nested switch is used at high level where we require sub conditions or cases. The inner and outer switch() case constant may be same. @@ -170,7 +215,8 @@ Enter first choice-t Enter second choice-t 2 Tails ``` - + + ## Review : Switch vs if else * Check the Testing Expression: An if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object. * Switch better for Multi way branching: When compiler compiles a switch statement, it will inspect each of the case constants and create a “jump table” that it will use for selecting the path of execution depending on the value of the expression. Therefore, if we need to select among a large group of values, a switch statement will run much faster than the equivalent logic coded using a sequence of if-elses. The compiler can do this because it knows that the case constants are all the same type and simply must be compared for equality with the switch expression, while in case of if expressions, the compiler has no such knowledge.