Switch Case in C

Learn via video course
FREE
View all courses
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
Topics Covered

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 e.g. 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.

Syntax of Switch Statement

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 the 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

Output –

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. (This 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 a 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 the 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 an integral value, so they are valid.

Valid switch expression example:

Output:

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

Output

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 in the switch clause. Moreover, they 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:

Output:

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 a 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 labels cannot have variables, only constant integral values are allowed.

Example for Invalid case values in Switch

Output:

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

Output:

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:

Output:

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:

Output:

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

Output:

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 a continue statement inside a switch will not affect 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 the if..else if ladder. Below is a C program that implements this using switch.

Program:

Output 1:

Output 2:

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 print 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 Operations 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 Operations 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 to declare a character variable and read the operator + 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:

Output 1:

Output 2:

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:

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 the 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 the 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 needs to be evaluated inside switch().All the Expressions inside the if() and else if() clause of if..else-if ladder needs to be evaluated one by one till one of the expressions 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 the 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 is 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 is 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 multiple 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 the 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 from, 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 a few practical applications of switch and their 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.