Falling Through a Switch-Case Structure

C language keywords often used in a switch-case structure are switch, case, default, and break. Only switch and case are required. You can omit the default condition. And the break keyword is used to avoid execution falling through the structure, yet sometimes that may be a useful effect.

For example, when you must match multiple conditions, stacking up a series of case statements allows you to match the multiple conditions to the same set of statements. This trick is used often for menu systems:

switch(input)
{
    case 'X':
    case 'x':
    case 'Q':
    case 'q':
        /* quit/exit the program */
...

These four case comparisons match both upper and lower case letters X and Q. The same statements execute whether the value of variable of variable input is X, x, Q, or q.

As another example, the following code attempts to slice up a string into individual words. A clutch of case statements match various characters that might appear after a word in a sentence. Execution falls through each one so that one set of statements executes for all the matching conditions.

#include <stdio.h>

int main()
{
    char string[] = "Hello there strange little planet\n";
    int x = 0;

    while( string[x] )
    {
        switch( string[x] )
        {
            case ' ':
            case '.':
            case ',':
            case '!':
            case '?':
            case ';':
            case ':':
            case '\n':
                putchar('\n');
                break;
            default:
                putchar( string[x] );
        }
        x++;
    }

    return(0);
}

The while loop processes the entire string. Within the loop, a switch-case structure examines various characters. If the character is a word separator, a newline is output otherwise the character in the string is output, building a word.

Here’s a sample run:

Hello
there
strange
little
planet

The fall-through ensures that more code isn’t required to process the various word-terminating characters. Further, if you forgot a character, you could easily add another case statement to match it.

Naturally, this code isn’t without its problems.

First, it might be easier to use a ctype function to check for word boundaries. Still, if I were coding this type of solution off the top of my head, I’d probably use a switch-case structure instead of a ctype function.

Second, the code catches spaces between words well, but has difficulty when two separators fall between words. So if a word is followed by a comma and a space, the output shows a blank line.

As a test, if array string[] is changed to read "Hello there strange, little planet\n", the output looks like this:

Hello
there
strange

little
planet

The blank line is caused by the space that follows the comma: For each character a newline is output.

In next week’s Lesson, I present a clever trick to resolve this issue.

Leave a Reply