Switch Case in C Programming

The switch statement in C is a multiway branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression.
It mainly consists of a number of cases, allowing the user to enter the case they want to access. Once the case is entered, the command at that very case is executed without wasting much time.

  • Case labels must be constants and unique.
  • Case labels must end with a colon ( : ).
  • we can't use float value.

Syntax of switch case

switch (expression) {
    case value1:
        // Code to execute if expression matches value1
        break; 
    case value2:
        // Code to execute if expression matches value2
        break;
    // ... more cases as needed

    default: 
        // Code to execute if no case matches
}

expression: An expression that must evaluate to an integer or character type.

case values: Constant integer or character expressions. The switch expression is compared to each case value.

Code blocks: The statements to be executed if the switch expression matches the corresponding case value.

break: Used to exit the switch block immediately after the matching code block is executed. This prevents "fall-through" to subsequent cases.

default: An optional section that executes if none of the case values match the switch expression.

Example
 /* C program for simple calculator by SmallCode using Switchcase. */
#include<tdio.h>
int main()
{
    int num1, num2;
    float result;
    char ch;
    printf("Enter first number: ");
    scanf("%d", &num1);
    printf("Enter second number: ");
    scanf("%d", &num2);
    printf("Choose the operation you want to perform (+, -, *, /, %): ");
    scanf(" %c", &ch);
    result = 0;
    switch(ch)
    {
        case '+':
            result = num1 + num2;
            break;
        case '-':
            result = num1 - num2;
            break;
        case '*':
            result = num1 * num2;
            break;
        case '/':
            result = (float)num1 / (float)num2;
            break;
        case '%':
            result = num1 % num2;
            break;
        default:
            printf("Invalid operation");
    }
    printf("Result: %d %c %d = %f", num1, ch, num2, result);
    return 0;
}