Search for Courses, Topics
certificate icon
Certificate

Learn on Scaler Topics and get certified.

static-certificate

Switch Case in C

Learn about Switch Case in C

1 Aug 2021-17 mins read
quiz
Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Overview

Decision control Statements in C language are used to decide the order of execution/flow of control in a program by making a decision based on a condition. For eg. if, else if etc.

Switch statement is one of the decision control statements of C language, which is primarily used in a scenario where the user has to make a decision between multiple alternatives.

Scope

  • In this article we will understand what are switch statements and look at its syntax.
  • We will understand how switch case works and the rules we need to abide by while using switch case.
  • We will also see the difference between switch and if-else statements.

Syntax of Switch Statement

switch (<Expression>) {
    // Expression evaluates to a single value.

 case <Value1> : //Case is picked when expression gives Value1. 
                 <Statement1>;
                 <Statement2>;
                 break;
 case <Value2> :
                 <Statement1>;
                 <Statement2>;
                 break;
 .
 . //So on.
 default : // When value of expression didn't match with any case
                 <Statement1>;
                 <Statement2>;
                 break;
}

How does C switch statement work

  1. First, the <Expression> inside the switch clause is evaluated to an integral constant.

  2. Its result is then compared against the case-value inside each case statement.

  3. If a match is found, all the statements following that matching case label are executed, until a break or end of switch is encountered. This is a critical statement. Also, please note that for any statement to execute inside a switch, it must be under any one case or under default.

Consider the example: Print English words, given a digit between 0-9. Below is how the implementation in Switch looks

int a = 9;
switch (a) {
 case 1: printf("I am One\n");
         break;
 case 2: printf("I am Two\n");
         break;
 case 3: printf("I an Three\n");
         break;
 case 4: printf("I am Four\n");
         break;
 case 5: printf("I am Five\n");
         break;
 case 6: printf("I am Six\n");
         break;
 case 7: printf("I am Seven\n");
         break;
 case 8: printf("I am Eight\n");
 case 9: printf("I am Nine\n");
 case 0: printf("I am Zero\n");
 default: printf("I am default\n");
}

Output –

The output of this switch is :
I am Nine
I am Zero
I am default

Explanation: The a variable value is 9, this is compared against the case values and a match is found. All the statements following case 9 are executed until a break statement or end of switch are encountered. Since there are no break statements(break is optional), all the statements following case 9 are executed. (Which is a weird output, if we gave 9 as input, we only want to print I am Nine as output, so we have to write break immediately after printf(“I am Nine”) to stop the flow)

For instance, If the a value is 5 instead of 9 in the above switch block. The output of the switch would be: I am Five. That’s it. This is because there is a break statement following case 5. Which interrupted the flow and control came out of the switch block.

So, as seen in the above example the flow of control in a switch is determined by the presence of break inside the case:

  • If break is present, after the matching case statements are executed control will come out of the switch

  • If break is not present after the matching case statements are executed it will continue to execute all the statements in the below cases including default, till the end of switch statement.

  • If no match is found between in switch and s in case, then

  • control goes to default block if it exists( default is optional ),

  • If default block is not written in the switch then, control comes out of switch and no case block is executed.

Flowchart of Switch Case in C

Flowchart of Switch Case in C

Rules of C Switch Statement

Below are the points to keep in mind when using switch statement.

  1. The <Expression> inside the switch clause must evaluate to a single integral value. This means the expression can only be an integer expression or character expression (Because a char is nothing but an ASCII value)

Valid Expressions: Constant expressions: 2 + 3, 9 * 16 % 2, 10 / 2 + 5, ‘a’ , ‘a’ + 1 etc. All these expressions evaluate to Integer constants, so they are valid.

Variable expressions (Assume int a,b; and Char c): a, a – b, c * a – 4,c + 1, etc. int and char are considered integral and valid in switch, and all the expressions evaluate to integral value, so they are valid.

Valid switch expression example:

switch (2+3) {
 case 5:
         printf("2+3 makes 5");
         break;
 case 4:
         printf("2+3 is not 4");
         break;
}

Output:

2+3 makes 5

Explanation: The switch(2+3) is evaluated and the integral value obtained is 5, which is then compared one by one with case labels and a matching label is found at case 5:. So, printf(“2+3 makes 5”) is executed and then followed by break; which brings the control out of the switch statement.

Other examples for valid switch expressions: switch(2+3), switch(9*16%2), switch(a), switch(a-b) etc.

Invalid Expressions:

Constant expressions: 4.5,10.0 / 7.1, “I am String” etc.( Basically anything that doesn’t evaluate to an integral value). 4.5 and 10.0/7.1 are float values that are invalid. “I am String” is a string constant that is different from the character constant and is invalid.

Variable expressions (Assume float a; double b;) : a,b, a + 4.5, b * 10 etc. Float and double are invalid datatypes in switch expressions.

Example of an Invalid switch

switch (4.5) { //Switch will throw an error
 case 5:
         printf("I am 5");
         break;
 default:
         printf("I am default");
         break;
}

Output

**error:** statement requires expression of integer type (‘double’ Invalid)

Explanation:

Switch statement only supports Integral data types, Any other data types will throw an Invalid type error.

Other examples for Invalid switch: switch(4.5) , switch(10.0/7.1), switch(a + 4.5) etc.

The part of the case clause must be a constant integral value or a constant expression followed by a colon. It cannot contain any variables unlike the in the switch clause. Moreover, the should only be an Integral/Character constant.

Valid Case Values:

2, 2 – 3, 9 * 16 % 10, 10 / 7, ‘a’, ‘a’ + ‘b’ etc. All these expressions evaluate to a constant integer value, hence all of them are valid case labels.

Example for valid case values in Switch:

switch (-2) {
 case 2-4:
         printf("I am -2");
         break;
 case 2:
         printf("I am 2");
         break;
 case 10/7:
         printf("I am 1");
         break;
 default:
         printf("I am default");
         break;
}

Output:

I am -2

Explanation: The switch(-2) value is compared with the case label and a match is found at case 2-4: because 2-4 evaluates to -2. So prinf(“I am -2”) statement is executed followed by break which brings the control outside the switch.

Invalid Values(Assume int a,b; float c; char d):

c, 2.3, 10.0/7.0, d + 1, a – b, c * a – 4, c + 1 etc. 2.3 and 10.0/7.0, both evaluate to a float constant which is invalid inside case label. c, d + 1, a – b, c * a – 4 and c + 1, all contain variables in them. Case label cannot have variables, only constant integral values are allowed.

Example for Invalid case values in Switch

switch (-2) { //Switch will throw  an error
 case 2.3:
         printf("I am -2");
         break;
 case 2.3:
         printf("I am 2.3");
         break;
 case 10.0/7.0:
         printf("I am not 1");
         break;
 default:
         printf("I am default");
         break;
}

Output:

error: expression is not an integer constant expression. Case 2.3:

Explanation:

The Constant expressions inside the case label must be integral Any other datatype would throw an invalid type error.

3.Duplicate case values are not allowed. Even though the inside the cases might differ, two cases cannot have the same <value>.

Example Switch illustrating duplicate switch cases are Invalid

switch (-2) { //Duplicate case values are invalid!!
 case 2-4:
         printf("I am -2");
         break;
 case 4-6:
         printf("I am negative two");
         break;
}

Output:

Error: duplicate case value ‘-2’

Explanation:

The case labels case 2-4 and case 4-6 both evaluate to the same integral value ‘-2’. Which is not valid. Duplicate case labels are invalid in switch.

4.There can be any number of case statements with different s, but there cannot be multiple default statements. Only one default is allowed.

5.The default statement inside the switch is optional. The default statement is executed when no case value in the switch matches with switch expression.

6.The break statement inside the switch is optional, if the break statement is executed, control will jump to the next line outside the switch block

Example without break:

switch (-2) {
 case 2-4:
         printf("I am -2");
 default:
         printf("I am negative two");
}
printf("I am out of switch!");

Output:

I am -2 I am negative two I am out of switch!

Explanation:

The switch(-2) matches with case 2-4: and all statements following case 2-4: are executed till a break or end of switch is encountered. So, both printf(“I am -2”) inside case 2-4: and printf(“I am negative two”) inside default are executed. After which control comes out the switch and printf(“I am out of switch!”) are executed.

Example with break:

switch(-2) {
 case 2-4:
         printf("I am -2\n");
         break;
 default:
         printf("I am negative two\n");
}
printf("I am out of switch!\n");

Output:

I am -2
I am out of switch

Explanation:

In this case, notice that there is a break statement after the printf(“I am -2\n”) in case 2-4, so after executing the printf, as per the behavior of switch case it tries to continue executing the below statements as well, but since it encountered break, control comes out of the switch and the printf(“I am out of switch!\n”) outside switch is executed. The default section is skipped.

7.Nesting of switch blocks is allowed, which means, it is completely valid to write an entire inner switch block inside one of the case/default statements of an outer switch.

Example of Nested Switch

int a = 5;
int b = 10;
switch (a) {  //Outer switch

 case 25/5:
             switch (b) {  // Inner switch. 
               case 100/10:
                     printf("I am inside two switches!!\n");
                     break;
               default:
                     printf("me too!\n");
             }
             break;
 default:
             printf("I am default\n");
}

Output:

 I am inside two switches!! 

Explanation:

switch(a) is evaluated and it matches with case 25/5 So, switch starts executing all the statements below case 25/5. The inner switch is executed. switch(b)is evaluated and it matches with 100/10 So printf and break inside case 100/10 are executed and after the break, control comes outside the inner switch back to the outer switch After the Inner switch is evaluated, the break is executed in case 25/5 Control comes out of the outer switch

8.Writing continue statement inside a switch will have no effect on the flow, unlike a loop.

9.Finally, flower braces {} are not required for case/default statements and any statements written above the first case statement are ignored by switch.

Example

#1 Given a digit from 0-9 print the English word for the digit using a C program

Solution:

This is the example use case we discussed in the Introduction section of this article, we have already seen that this program can be implemented using if..else if ladder. Below is a C program that implements this using switch.

Program:

#include <stdio.h>
 
int main() {
 
 int digit; 
 
 printf("Enter digit:");
 scanf("%d",&digit); //Input digit
 
 switch (digit) { //Writing a case for every digit in 0-9
 
   case 1:
           printf("One\n");
           break;
   case 2:
           printf("Two\n");
           break;
   case 3:
           printf("Three\n");
           break;
   case 4:
           printf("Four\n");
           break;
   case 5:
           printf("Five\n");
           break;
   case 6:
           printf("Six\n");
           break;
   case 7:
           printf("Seven\n");
           break;
   case 8:
           printf("Eight\n");
           break;
   case 9:
           printf("Nine\n");
           break;
   case 0:
           printf("Zero\n");
           break;
   default:
           printf("Invalid Digit\n");
 }
 
 return 0;
}

Output 1:

Enter digit:0
Zero

Ouput 2:

Enter digit:10
Invalid Digit

Explanation:

  • We took an input variable ‘digit’ from the user and read an integer using scanf
  • A switch statement is written with cases 0-9 and for each case, we are printing the corresponding English word for that digit.
  • If the input integer is not a value between 0-9 we wrote a default case to handle that scenario, we print ‘Invalid Digit’

#2 C program that implements a calculator that does the below

  • Take two integers as input
  • Perform Addition/Subtraction/Multiplication/Division Operation on the two inputs.
  • Also, Take input from the user to know which operation to perform

Solution: This is a classic use case of switch. We have in front of us four choices/operations according to the program statement above, Addition/subtraction/multiplication/division. This is the kind of scenario where Switch works best. And here’s how we can interpret the problem statement.

  • Take two integers as input: We declare two integer variables and read two variables using scanf.

  • Perform Addition/Subtraction/Multiplication/Division Operation on the two inputs.

  • Also, Take input from the user to know which operation to perform:

    • We ask the user which operation he wants to perform. One simple solution is, declare a character variable and read the operator + or – or or /. Based on the character given as input, we can decide on the operation.*

    • The character variable which contains the operator becomes our switch expression.

    • Inside the switch, we write the cases one for each operator viz., case ‘+’ / case ‘-’ / case ‘*’ / case ‘/’. And the corresponding operation statement inside the case

    • We handle the invalid operator scenario using default.

    • Because a character is nothing but an Ascii value, it is perfectly valid to write it in switch expression and case label.

We took a simple implementation of an arithmetic calculator to understand the use case of switch. The arithmetic calculators in the real world are a bit more complicated as we know they support several other operations other than addition/ subtraction/ multiplication/ division. Also, they support more than two integer variables. They also support float variables. But yes, No matter how many inputs or operations, they could in fact be implemented using switch and could be considered an extension to our example.

Program:

#include <stdio.h>
 
int main(void) {
     int a , b;  //The two inputs
     char operation; //Variable to read operation
 
     printf("Enter the operator(+,-,*,/):");
     scanf("%c",&operation);
    
     printf("Enter the two inputs:\n");
     scanf("%d%d",&a,&b);
 
     switch (operation) {  // Case for every operation.
         case '+':
                   printf("Addition of %d and %d is %d\n", a, b, a + b);
                   break;
         case '-':
                   printf("Subtraction between %d and %d is %d\n", a, b, a - b);
                   break;
         case '*':
                   printf("Multiplication between %d and %d is %d\n", a, b, a * b);
                   break;
         case '/':
                   printf("Dividing %d by %d gives %d\n", a, b, a/b);
                   break;
         default:
                   printf("%c is Not a valid operator\n",operation);
     }
 return 0;
}

Output 1:

Enter the operator(+,-,,/):
Enter the two inputs:
5
4
Multiplication between 5 and 4 is 20

Output 2:

Enter the operator(+,-,*,/):%
Enter the two inputs:
3
4
% is Not a valid operator

Explanation:

  • Read the operator into a character variable.
  • Read the two input values into two integer variables.
  • Write a switch statement with four cases one for each operator +, -, *, /. And inside that case perform the corresponding operator and output the result.
  • Handle the case with the invalid operator using default.

Nested switch in C

Switch statement supports nesting similar to any if, else, etc. It means, we can write a switch inside a switch and keep on doing it any number of times. Let us look at a simple example to understand it better

Consider the below code snippet:

int ch1,ch2;
ch1 = 1;
ch2 = 9;
switch (ch1) {
 case 1:
         switch (ch2) {
           case 9:
                 printf("I am inside the inner switch!!");
                 break;
           default:
                 printf("I am inside but I am useless!");
         }
         break;
 default:
       printf("I am not allowed to go to inner switch :(");
}

Explanation:

The nested switch statements above together print “I am inside the inner switch!!” as output. And here’s how it works:

  • First, switch(ch1) is evaluated and case 1 is picked. Once Inside case 1, the inner switch is invoked, and switch(ch2) is evaluated, which picks case 9, and executes the statements inside it.
  • Printf inside case 9 is executed and then break is executed, which brings the control outside the switch(ch2) to the next statement outside, which is break; in case 1 of the outer switch(ch1).
  • Once the break in the outer switch is executed, the control comes outside of switch(ch1).

The flow of outer switch stepwise:

  1. switch(ch1) is evaluated and case 1 is picked
  2. The inner switch statement is executed. And the break is executed
  3. And Control is out of the switch.

The flow of inner switch stepwise:

  1. The inner switch statement is executed in step 2 of the outer switch execution, and there switch(ch2) is evaluated.
  2. Control jumps to case 9 and the printf statement inside case 9 is executed.
  3. The break is executed and control comes out of the inner switch. And the next statement outside the inner switch is executed.
  4. The next statement is the break-in case 1 of the outer switch.

Switch vs. If else

SwitchIf else
Only one need to be evaluated inside switch().All the Expressions inside the if() and else if() clause of if..else-if ladder needs to evaluated one by one till one of the expression evaluates to true.
Easy to read and interpretWhen the number of cases is more, it is difficult to read and interpret.
Only Integral expressions are validSupports other datatype expressions/values as well
Fast compared to if-else ( we shall see why in the next section)Slow compared to switch ( we shall see the reason why in the next section)
If a matching case is found, all the statements following that case are evaluated till a break or end of switch is found.Only one if/else-if block is executed and control jumps to the end of if..else if ladder.
Switch can only contain one expression, and case labels can only contain constant values.Both Expression/Constant values can be written in any if and else if conditions.

Why do we need a C switch case?

Although we know that the logic behind a switch can easily be implemented using an if..else..if ladder, Below are the main reasons why we opt for switch in certain cases:

  • When there a huge number of alternatives to choose from, using switch compared to if-else-if will make the program run faster. Reason: This is because of the compiler optimization that is possible in switch but not in if..else. If the number of cases is more, the compiler implements the switch as a look-up table/hash which essentially means that it takes the same time to access the topmost case as it takes to access the last case in a switch statement.

This is not the same for the if-else ladder where all the if and else if blocks are stored as a list and it takes more time to access the bottommost else-if as all the expressions of the above else-ifs need to be evaluated first.

  • When there a huge number of alternatives, switch would be much more neatly structured and readable when compared to if-else if.
  • Especially, the cases, where there are menu items to choose from.Ex: calculator, restaurant orders, etc. a switch is preferred over if-else-if. The reason is simple, menu items generally mean multiples options/alternatives to execute. And this is the use case where switch works best as it optimizes the time and makes the code run faster and also makes code a lot more readable.

Important points to C Switch Case

Below is a summary and some of the important points to keep in mind when working with switch.

  1. A switch is a decision control statement that is similar to the if-else if ladder, but is preferred over the if-else if when there are a multiple numbers of alternatives( menu items ) to choose, as it is faster and more readable.
  2. Only Integral values are allowed inside the case label, and the expression inside the switch must evaluate to a single integral constant.
  3. Variables are not allowed inside the case label, but integer/character variables are allowed for switch expression.
  4. Break and default are optional.
  5. Nesting is valid for switch.

Conclusion

We have reached the end of the Article. Let me conclude by sharing few practical applications of switch and its disadvantages in practical usage.

Applications of Switch:

  • Arithmetic calculator
  • ATM operations like withdrawal, transfer, etc.
  • Restaurant Orders and bill calculation

Disadvantages of Switch:

  • Supports only Integral expressions/constants.
  • Does not support more than one expression. If more expressions need to be evaluated, another switch should be added and nested.
Challenge Time!
quiz Time to test your skills and win rewards! Note: Rewards will be credited after the next product update.