• Home
  • 2.10 Multiple case Labels in switch

2.10 Multiple case Labels in switch

View Categories

2.10 Multiple case Labels in switch

< 1 min read

Table of Contents

Multiple case labels can be placed before the same block of statements when several values should produce the same result. Each matching label transfers execution to the same code.

#include <stdio.h>

int main()
{
    int day = 6;

    switch (day)
    {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
            printf("Weekday\n");
            break;

        case 6:
        case 7:
            printf("Weekend\n");
            break;

        default:
            printf("Invalid day\n");
    }

    return 0;
}

Example Output #

Weekend

Explanation #

The value of day is 6, so execution starts at:

case 6:

There are no statements immediately after case 6, so execution continues to case 7 and then reaches the shared statement:

printf("Weekend\n");

The same pattern is used for the weekday cases. Values 1 through 5 all lead to the same printf() statement.

This is intentional fall-through between consecutive case labels. The break after the shared statement prevents execution from continuing into the next group.

This technique is useful when multiple values need identical handling without duplicating the same code.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *