A switch statement—or simply a case statement—is a control flow mechanism that determines the execution of a program based on the value of a variable or an expression.

Using a switch statement allows you to test multiple conditions and only execute a specific block if the condition is true. Although it works similarly to an if…else if….else statement, the syntax is simpler and easier to read and manage.

This tutorial focuses on showing you how to create and work with switch statements in C programming.

Basic Usage

The switch statement is easy to implement. The general syntax is as shown below:

switch (expr) {


    casevar1:

// code


        break;


    casevar2:


     //code


        break;


    casevar3:


    // code


        break;


    casevarN:


     // code


        break;


    …


    ….


    ….


    default:

//code

}

How It Works

The switch statement implements a simple logic to evaluate each of the case blocks.

It starts by evaluating the expression inside the switch block. Then, it compares the value from the switch block against each case block.

Once it locates a match inside one of the defined case blocks, it executes the code inside that block until it encounters the break keyword.

If it does not encounter a match in either of the defined case blocks, it jumps to the default statement and executes the code inside it. The default block is optional and omittable if there is no required action for a non-matching scenario

NOTE: It is good to ensure each case statement terminates with a break statement to prevent all the statements after the matching block from executing.

C Switch Case Statement Example

Let us illustrate the switch statement with a very simple example:

#include

intmain() {

int var = 5;

switch (var) {


case3:

printf(“The value is 3”);

break;


case4:

printf(“The value is 4”);

break;


case5:

printf(“The value is 5”);

break;

default:

printf(“The value is neither 3, 4 nor 5”);


    }


return0;

}

If we run the above example, we should get an output similar to the one below:

The following flow diagram illustrates the logic of the above program:

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/word-image-595.png" data-lazy- height="1920" src="data:image/svg xml,” width=”1480″>

A Nested Switch Statement

C allows you to have nested switch statements inside a switch statement. The nested switch statement ties to the value of the outer switch.

Consider the following example:

#include

intmain() {

int dept = 5;


intaccess_code = 2028;

switch (dept) {


case1:

switch (access_code) {


case2021:

printf(“[ ] Valid access code!”);

break;

default:

printf(“[-] Invalid access code!”);


            }

break;

default:

printf(“[-] Only Department 1 is allowed!”);


    }


return0;

}

In the example above, we implement two switch statements. The first checks if the dept provided is 1. If true, it proceeds to the next switch block and checks for the valid access code.

If the dept value is not one, the execution moves to the default block.

The following is the execution of the code above with correct and incorrect dept and access code.

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/word-image-596.png" data-lazy- height="476" src="data:image/svg xml,” width=”716″>

In the first example, both the dept and access code are correct; thus, the execution never reaches the default blocks.

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/word-image-597.png" data-lazy- height="486" src="data:image/svg xml,” width=”698″>

In the second example, both the dept and access code are incorrect; hence, the execution immediately jumps to the first default block.

Guidelines for Switch Statements

The following are quick guidelines worth noting when creating switch statements in C.

  1. You must pass an expression to the switch keyword.
  2. Case statements must check for unique values
  3. Terminate each case block using the break keyword.
  4. You can nest multiple switch statements.
  5. You can include a default statement when an action is necessary for non-matching cases.

Conclusion

This guide has walked you through the basics of creating and using C switch statements. Switch statements are useful when you have complex decision cases that might be difficult to implement with the and if else statement.

About the author

<img alt="" data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/john-150×150.png61213d27e0453.jpg" height="112" src="data:image/svg xml,” width=”112″>

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list