Back to course

Conditional Logic: The 'switch' statement

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 16: Conditional Logic: The switch Statement

The switch statement is an efficient alternative to long if-else if ladders when comparing a single variable against multiple constant values.

Syntax

c switch (expression) { case constant1: // Code block 1 break; case constant2: // Code block 2 break; default: // Code if no case matches (optional) }

Key Rules:

  1. The expression must evaluate to an integer or character type.
  2. constant1, constant2, etc., must be constant integer expressions (literals or defined constants, not variables).

Example: Day Checker

c #include <stdio.h>

int main() { int day = 3;

switch (day) {
    case 1:
    case 7:
        printf("Weekend.\n");
        break;
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
        printf("Weekday.\n");
        break;
    default:
        printf("Invalid day number.\n");
}
return 0;

}

The Importance of break

If you omit the break keyword, execution will fall through to the next case block, even if the condition for that case is not met. While useful for grouping (like cases 1 and 7 above), this is usually undesirable and a source of bugs.