About usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar

Switch Statement in C/C++

Switch statements are pretty popular in software engineering technical interviews. If you are preparing for a software-engineering technical interview, you must know them and understand how to use them well. In this article, we will discuss switch statements in C or C++ language.

This article will cover the following concepts:

  • What Is a Switch Statement in C/C++?
  • Important Points About Switch Case Statement in C/C++
  • Valid Expression for Switch
  • Flow Chart of a Switch Statement
  • Examples of Switch Statements
  • FAANG Interview Questions on Switch Statement in C/C++
  • FAQs on Switch Statement in C/C++

What Is a Switch Statement in C/C++?

The switch statement in C/C++ takes the value of a particular variable and compares it with multiple cases. Once it finds the matching case, it executes the block of statements associated with that particular case. You can look at it as an alternative for long if-else statements. 

In the switch statement, each case in a switch statement block has a different value, which acts as a unique identifier. The value provided to the switch statement is compared with all the cases inside it until it finds the case representing the same value. 

A provision for a default case also exists that is similar to the else block in an if-else statement. If there is no matching case with provided value, then the default statement is executed.

The default case inside the switch statement is optional. If our value does not match with any case label and the switch statement does not include a default case, then no case will be executed.

Syntax:

// val - it is the value provided to the switch block

switch(val)

{

    case t1: 

        // this block gets executed if t1 == val.

        break;

    case t2: 

        // this block gets executed if t2 == val.

        break;

    default: 

        // this block gets executed if val doesn't match any of the above cases.

}


In the above syntax, the execution involves comparing the val with the values of each case label (i.e., with t1, t2).

  • If it matches with any label, then the corresponding statements after the matching label get executed. 
  • If there is no match of the value, then the default statements get executed.


If we do not use the loop control statement break at the end of the block for each case, then all statements after the case with the matching label are executed. This case is known as a fall-through switch case.

Important Points About Switch Case Statement in C/C++

  • The expression provided in the switch statement should result in a constant value. 
  • The data types we can use inside the switch are int, char, string, and bool.
  • In the switch statement, duplicate case values are not allowed
  • If the switch case statement does not have a default case statement, it will run because the default statement is optional. 
  • In the execution of the statements that lie within the matching case, when a break statement is reached, it terminates the switch, and the control jumps out of the switch statement. 
  • If we don't use the break statement, the execution will continue for all the cases after the matched case. The execution of cases occurs until we either reach the end of the switch statement or encounter a break statement.
  • We can have one switch statement inside the other, which Means nesting of switch statements is possible. 

Valid Expression for Switch

If an expression after evaluating gives a constant value, that expression is a valid expression for the switch statement. 

Examples:

// Constant expressions

switch(5+23) is equivalent to switch (28), and it is valid

switch(1*6+4/2) is equivalent to switch(8) and it is valid


// If variable expressions have assigned fixed values, then they are allowed, and hence, they make a valid expression. 

switch(p*q)

switch(d+c)

Flow Chart of a Switch Statement:

Have a look at the following flowchart to understand switch statements better:

Example Implementations of Switch Statements

Now we’ll understand how switch statements work through a few examples:

Example 1:

// Implementation of switch statement in C/C++. 

#include <stdio.h>

int main()

{

   int val = 10;

   switch (val)

   {

       case 10: 

               printf("Case 1 matched");

               break;

       case 20: 

               printf("Case 2 matched");

               break;

       case 30: 

               printf("Case 3 matched");

               break;

       default: 

               printf("None of the cases matched");

               break; 

   }

   return 0;

}


Output

Case 1 matched

Example 2:

// Implementation of a switch statement in C/C++. 

// Here, because we have not used any break statement, the execution of all the cases after matched cases also occurs. 


#include <stdio.h>

int main()

{

    int val = 10;

    switch (val)

    {

    case 10:

        printf("Case 1 matched\n");

    case 20:

        printf("Case 2 matched\n");

    case 30:

        printf("Case 3 matched\n");

    default:

        printf("None of the cases matched\n");

    }

    return 0;

}


Output

Case 1 matched

Case 2 matched

Case 3 matched

None of the cases matched


Time Complexity

O(1) because we are not running any loop, and there are constant operations only.

Auxiliary Space

O(1) because we are not using any extra space.

FAANG Interview Questions on Switch Statement in C/C++ 

  • What is the valid expression for switch statements? 
  • How does the default case contribute to and work in a switch statement?
  • What are some data types that we can check inside switch statements?
  • What are the advantages and disadvantages of switch statements? 
  • Convert the given pseudocode into nested switch statements. 

    if(condition1)

           // code

     End if

     else 

         if(condition2)

            // code

         End if

         else if(condition3)

                        // code

                     End else if

                     else

                        // code

                     End else

         End else   

FAQs on Switch Statement in C/C++

Question 1: What is the advantage of switch statements over if-else? 

The main advantage of using switch statements over if-else is that the switch statement is more efficient than the nested if-else statements.

A switch makes code cleaner and easy to understand when we have to combine cases. So, because of easier syntax and readability, switch statements are sometimes more preferred over if-else statements. 

Question 2: What happens if we place the default case before any other case statement instead of placing it last?  

Default case in switch statements executes when there is no matching case value found. In switch statements, we can place the default block anywhere. The position of the default block does not matter; it will still execute only when the program finds no case matching with the desired value.

So, if we place a default case before any other case, It will not affect the functionality of the default case. If we don't use the break statement at the end of the default block, then all the cases after it will get executed until we either reach the end of the switch statement or encounter a break statement.

Are You Ready to Nail Your Next Coding Interview?

Whether you’re a Coding Engineer gunning for Software Developer or Software Engineer roles, or you’re targeting management positions at top companies, IK offers courses specifically designed for your needs to help you with your technical interview preparation!

If you’re looking for guidance and help with getting started, sign up for our free webinar. As pioneers in the field of technical interview prep, we have trained thousands of Software Engineers to crack the most challenging coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!

Sign up now!

————

Article contributed by Omkar Deshkmukh

Attend our Free Webinar on How to Nail Your Next Technical Interview

Recommended Posts

All Posts