• Home
  • 2.9 Nested switch Statements

2.9 Nested switch Statements

View Categories

2.9 Nested switch Statements

< 1 min read

Table of Contents

A switch statement can be placed inside another switch statement. The inner switch is evaluated only after execution enters the block containing it.

#include <stdio.h>

int main()
{
    int category = 1;
    int option = 2;

    switch (category)
    {
        case 1:
            switch (option)
            {
                case 1:
                    printf("Category 1, Option 1\n");
                    break;

                case 2:
                    printf("Category 1, Option 2\n");
                    break;

                default:
                    printf("Invalid option\n");
            }
            break;

        case 2:
            printf("Category 2\n");
            break;

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

    return 0;
}

Example Output #

Category 1, Option 2

Explanation #

The outer switch evaluates category:

switch (category)

Since category is 1, execution enters case 1.

That case contains another switch:

switch (option)

The value of option is 2, so case 2 of the inner switch executes.

The break inside the inner switch exits the inner switch. The break belonging to the outer case 1 then exits the outer switch.

The two switch statements have separate case labels and separate control flow.

Powered by BetterDocs

Leave a Reply

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