The ‘case’ Keyword in C Programming

C Programming @ Freshers.in

In C programming, the ‘case’ keyword is an essential component of switch statements, allowing you to define specific code blocks to execute based on the value of an expression. This article provides a comprehensive explanation of the ‘case’ keyword, its role in switch statements, and offers real-world examples to illustrate its functionality.

Understanding the ‘case’ Keyword

The ‘case’ keyword is used within a switch statement to specify different code blocks that will be executed depending on whether the value of the expression matches a particular case label. It facilitates conditional branching within the switch statement.

Syntax:

switch (expression) {
    case constant_1:
        // Code to execute when expression matches constant_1
        break;
    case constant_2:
        // Code to execute when expression matches constant_2
        break;
    // Additional cases...
    default:
        // Code to execute when none of the cases match
}

Example 1: Using ‘case’ in a Switch Statement

#include <stdio.h>

int main() {
    int choice = 2;
    switch (choice) {
        case 1:
            printf("Option 1 selected\n");
            break;
        case 2:
            printf("Option 2 selected\n");
            break;
        case 3:
            printf("Option 3 selected\n");
            break;
        default:
            printf("Invalid choice\n");
    }
    return 0;
}

Output:

Option 2 selected

In this example, the value of choice is 2, so the code block associated with ‘case 2’ is executed. The ‘break’ statement ensures that the switch statement exits after the matched case is executed.

Example 2: Using ‘case’ with Enumerations

#include <stdio.h>

enum Day { MON, TUE, WED, THU, FRI, SAT, SUN };

int main() {
    enum Day today = WED;
    switch (today) {
        case MON:
        case TUE:
        case WED:
        case THU:
        case FRI:
            printf("It's a weekday!\n");
            break;
        case SAT:
        case SUN:
            printf("It's the weekend!\n");
            break;
        default:
            printf("Invalid day\n");
    }
    return 0;
}

Output:

It's a weekday!

In this example, the ‘case’ labels are used to group multiple constants together. When today is set to WED, the weekday block is executed due to the fall-through behavior of cases.

Common Use Cases for ‘case’

  1. Switch Statements: ‘case’ is primarily used within switch statements to control the flow of program execution based on the value of an expression.
  2. Grouping Constants: ‘case’ labels can be used to group multiple constants together for shared code execution.
  3. Enumerations: ‘case’ is commonly used with enumeration types to provide human-readable labels for specific values.
Author: user