Switch-Case Execution

The switch-case structure is the most complex decision tool in the C language. Yes, the ternary operator is more cryptic, but a proper switch-case structure involves more keywords: switch, case, default, and break. The break keyword is what I feel makes the structure most interesting.

As a decision tool, switch-case handles multiple comparisons: The switch argument is compared with each case constant. Only when the comparison is true are the statements belonging to case executed. When no case argument matches, the statements belonging to default are executed — but even then, default is optional.

Below is code for a typical switch-case structure. The value of variable alpha is compared to the constants set after each of the case statements.

#include <stdio.h>

int main()
{
    int alpha = 5;

    switch(alpha)
    {
        case 1:
            puts("One");
            break;
        case 2:
            puts("Two");
            break;
        case 3:
            puts("Three");
            break;
        case 4:
            puts("Four");
            break;
        case 5:
            puts("Five");
            break;
        default:
            puts("Out of range");
    }

    return(0);
}

The last case statement’s constant value 5 matches the value of alpha, so “Five” is output. The break statement exits the switch-case structure. Here’s the output:

Five

Here’s the output when all the break statements are removed:

Five
Out of range

Because none of the preceding case statements matched 5, their statements don’t execute. But because break in the case 5: statement is removed, you also see statements from the default condition executed.

When the value of alpha is changed to 1 and the break statements are removed, here’s the output:

One
Two
Three
Four
Five
Out of range

Though the value of alpha doesn’t match subsequent case statement values, execution falls through to those statements anyway.

In a way, it helps to think of the case keyword as a label, not really a controlling part of the structure. Its value is compared, but the case statement itself isn’t a barrier; once a case statement rings true, execution cascades through the rest of the switch-case structure line-by-line. That is, unless a break statement is found.

Further, you can’t trick the compiler by setting two case statements with the same value. (And I wouldn’t know why such a thing would be practical.) If you attempt to set two case statements with the same value, the compiler generates a duplicate case value error. Seriously, if you need more statements for a match, put them all after a single case condition.

The fall-through effect of the switch-case structure can be an advantage. I’ll demonstrate how in next week’s Lesson.

Leave a Reply