English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structures

C Language Files

C Others

C Language Reference Manual

C Language switch Statements

In this tutorial, you will learn how to create a switch statement in C language programming through an example.

The switch statement allows us to execute one of many code blocks.

Although you can use if...else..if ladder to perform the same operation. However, the syntax of the switch statement is easier to read and write.

Syntax of switch ... case

switch (expression)
{
    case constant1:
      // Statement
      break;
    case constant2:
      // Statement
      break;
    .
    .
    .
    default:
      // Default statement
}

How does the switch statement work?

The expression (expression) is evaluated once and compared with the value of each case label.

  • If there is a match, execute the statements after the matching label. For example, if the value of the expression is equal to constant2, then execute case constant2The statements after :, until break is encountered.

  • If there is no match, the default (default) statement will be executed.

If break is not used, all statements after the matching label will be executed.

By the way, the default clause in the switch statement is optional.

Switch statement flowchart

Example: Simple Calculator

//The program creates a simple calculator
#include <stdio.h>
int main() {
    char operator;
    double n1, n2;
    printf("Enter an operator (+, -, *, /):");
    scanf("%c", &operator);
    printf("Enter two operands: ");
    scanf("%lf %lf", &n1, &n2);
    switch (operator)
    {
    case '+':
        printf("%.1lf + %.1lf = %.1lf", n1, n2, n1 + n2);
        break;
    case '-':
        printf("%.1lf - %.1lf = %.1lf", n1, n2, n1 - n2);
        break;
    case '*':
        printf("%.1lf * %.1lf = %.1lf", n1, n2, n1*n2);
        break;
    case '/':
        printf("%.1lf / %.1lf = %.1lf", n1, n2, n1 / n2);
        break;
        // No matching operator found ( +, -, *, /)
    default:
        printf("Error! The operator is incorrect");
    }
    return 0;
}

Output result

Enter an operator (+, -, *,): -
Enter two operands: 32.5
12.4
32.5 - 12.4 = 20.1

The operator entered by the user (-Stored in the operator variable. Moreover, two operands32.5and}}12.4are stored in the variable n1and n2in.

Since operator is -Therefore, the control of the program jumps to the statement

printf("%.1lf - %.1lf = %.1lf", n1, n2, n1-n2);

Finally,break statementTerminate this switch statement, operation completed.