How to use switch in C

About C 'switch' statement

In C programming, the switch statement is a control flow statement that is used to perform different actions based on different conditions.

It is used to test the equality of a variable against a list of conditions using case keyword. When it finds equality with a condition, the block of code under the case label condition is executed.

The switch statement is an organized alternative of writing many if..else statements. It provides a more readable and efficient way to handle multiple conditions.

Syntax of 'switch' statement

  • switch: The switch keyword begins the switch statement.
  • expression: The expression is a variable that is evaluated once and compared with each 'case' constant.
  • case constant1: case constant2:: Each case keyword is followed by a constant value and a colon ':'. The block of code under case statement is executed when the expression matches the constant. A switch statement can have as many case statements as required.
  • break: The break statement terminates the case as well as switch statement and gets the control out of the switch statement.
  • default:: The default case runs if no case constants match the expression. It is optional.

Create a 'switch' statement

A 'switch' statement has been created in the following example:

Example of 'switch' statement
Output of the above example
Excellent! your grade is A.

Explanation of code:

  • int marks = 90;: The line initializes an integer variable 'marks' with value 90. It will be used as expression in the 'switch' statement.
  • switch (marks): The 'switch' keyword begins the 'switch' statement with 'marks' expression. It tests the value of 'marks' and transfers control to the corresponding case label.
  • case 70:: If 'marks' is equal to 70, the code block under the case label 'printf("Well done, your grade is B.\n");' will be executed and the 'break;' statement will get the control out of the 'switch' block.
  • case 90:: If 'marks' is equal to 90, the code block under the case label 'printf("Excellent! your grade is A.\n");' will be executed and the 'break;' statement will get the control out of the 'switch' block. As the expression value is equal to the case value, the code block under this case will be executed.
  • default:: If 'marks' does not match any of the specified case values, the code block under the default label 'printf("Invalid marks\n");' will be executed.

Live Code Playground

In the following C code editor, you can practice by adding more cases to the following 'switch' statement. Click the 'Execute' button to execute the code; the executed output will be displayed in the following C Code Output frame. Practice until you become comfortable and proficient with your code.

C logo C Online Editor
C Code Output