switch case statement in C Programming

The switch case statement is used when we have multiple options and we need to perform a different task for each option.

Switch Case Statement

Before we see how a switch case statement works in a C program, let’s checkout the syntax of it.

switch (variable or an integer expression)
     case constant:
     //C Statements
     case constant:
     //C Statements
     //C Statements

Flow Diagram of Switch Case

C switch case

Break statement in Switch Case

Break statements are useful when you want your program-flow to come out of the switch body. Whenever a break statement is encountered in the switch body, the control comes out of the switch case statement.

Few Important points regarding Switch Case

1) Case doesn’t always need to have order 1, 2, 3 and so on. They can have any integer value after case keyword. Also, case doesn’t need to be in an ascending order always, you can specify them in any order as per the need of the program.

2) You can also use characters in switch case.

3) The expression provided in the switch should result in a constant value otherwise it would not be valid.
For example:
Valid expressions for switch –


Invalid switch expressions –


4) Nesting of switch statements are allowed, which means you can have switch statements inside another switch. However nested switch statements should be avoided as it makes program more complex and less readable.

5) Duplicate case values are not allowed.

6) The default statement is optional, if you don’t have a default in the program, it would run just fine without any issues. However it is a good practice to have a default statement so that the default executes if no case is matched. This is especially useful when we are taking input from user for the case choices, since user can sometime enter wrong value, we can remind the user with a proper error message that we can set in the default statement.

For any query or issue, feel free to discuss on http://discuss.eduguru.in