Coding

Switch Statement in C: Syntax, Examples and Common Mistakes

A switch statement in C compares one integer expression against a list of constant case values and jumps to the matching label, running statements from there until a break or the end of the body. The basic form is switch (expression) { case 1: ...; break; default: ...; }.

Switch statement syntax in C

switch (expression)
{
    case constant_expression_1:
        /* statements */
        break;
    case constant_expression_2:
        /* statements */
        break;
    default:
        /* statements when nothing matched */
}

The grammar is simply switch (expression) statement, where the statement is almost always a compound statement in braces. case and default are labels inside that body. They are only meaningful inside a switch, and the switch uses them only once, to decide where execution starts.

A first working example

#include <stdio.h>

int main(void)
{
    int day = 3;

    switch (day)
    {
        case 1:
            puts("Monday");
            break;
        case 2:
            puts("Tuesday");
            break;
        case 3:
            puts("Wednesday");
            break;
        default:
            puts("Unknown day");
    }
    return 0;
}

Example output:

Wednesday

The value of day is 3, so control jumps to case 3:, prints the line, and break leaves the switch. Change day to 9 and no case matches, so the default label runs and prints Unknown day.

What types can a switch use?

The controlling expression must have an integer type: char, signed or unsigned integers, or an enumeration. Each case value must be an integer constant expression, which means the compiler can work out its value at compile time. A literal such as 3, a character such as 'a', an enumerator, or an arithmetic expression built from those all qualify. A variable does not.

This is why C cannot switch on a string, a float or a double. For strings, use strcmp in an if / else if chain. For a floating-point value, compare ranges with if.

Character and enum switches are common:

enum color { RED, GREEN, BLUE };

const char *color_name(enum color value)
{
    switch (value)
    {
        case RED:   return "red";
        case GREEN: return "green";
        case BLUE:  return "blue";
    }
    return "unknown";
}

Here return leaves the function directly, so no break is needed. The return "unknown" after the switch handles values that are not one of the three enumerators.

How break and fall-through work

Once a label matches, execution does not stop at the next label. It keeps running statements in order until it reaches a break or the closing brace of the switch. Running on into the next label is called fall-through. This is the example from cppreference:

#include <stdio.h>

void func(int x)
{
    printf("func(%d): ", x);
    switch (x)
    {
        case 1: printf("case 1, ");
        case 2: printf("case 2, ");
        case 3: printf("case 3.\n"); break;
        case 4: printf("case 4, ");
        case 5:
        case 6: printf("case 5 or case 6, ");
        default: printf("default.\n");
    }
}

Example output for func(1), func(4) and func(8):

func(1): case 1, case 2, case 3.
func(4): case 4, case 5 or case 6, default.
func(8): default.

Calling func(1) prints three fragments because only case 3 has a break. Calling func(4) falls from case 4 through case 5 and case 6 into default.

Grouping several cases on one action

Stacking labels with no statements between them is the normal, intentional use of fall-through. All the labels point at the same statement:

switch (c)
{
    case 'a':
    case 'e':
    case 'i':
    case 'o':
    case 'u':
        vowels++;
        break;
    default:
        others++;
}

Microsoft's documentation shows the same pattern with 'a' through 'f' calling a hex-conversion function. When you fall through with statements in between, leave a comment saying it is deliberate, so the next reader does not "fix" it by adding a break.

The default label

If no case matches and there is a default label, control goes there. If there is no default, none of the switch body runs and the program continues after the closing brace. At most one default is allowed, and it does not have to be the last label. Putting it last is still the convention, because it makes fall-through behavior easier to read.

For an enum, many teams leave default out on purpose so the compiler can warn when a new enumerator is added and not handled. Whether it does depends on the compiler and its warning flags, so check your compiler's documentation rather than assuming.

Common mistakes

  • Missing break. The code compiles and runs, and then executes the next case too. If you see two outputs where you expected one, look here first.
  • Duplicate case values. Every constant must be unique within one switch. Two case 1: labels, or two labels that end up with the same value after conversion, are a compile error. A nested switch may reuse values because it has its own labels.
  • Non-constant case labels. case limit: fails if limit is an ordinary variable. Use a literal, an enumerator, or a #define. A const int variable is not an integer constant expression in C, so it does not work either.
  • Declarations with initializers inside the body. The switch jumps straight to a label, so any initialization that sits above it is skipped. Microsoft's documentation notes that declarations can appear at the head of the body but their initializations are not performed. If a case needs its own variable, give it its own block:
switch (command)
{
    case 1:
    {
        int count = read_count();
        process(count);
        break;
    }
    case 2:
        reset();
        break;
}

The braces limit count to case 1, so jumping to case 2 never bypasses its initialization.

  • Variable length arrays. If a variable length array is in scope at a case or default label, the entire switch must be in that scope. Declare the array before the whole switch or after the last label.

Switch or if / else if?

Use switch when you are choosing between several known integer values of one expression: command codes, enum states, characters from a parser. Use if / else if when the conditions involve ranges, several variables, floating-point values or strings. A switch with two cases is usually clearer as a plain if.

The standard does not promise any speed difference. A compiler may implement a switch as a jump table, a series of comparisons or a binary search, depending on the case values. Pick the form that reads best and profile if speed matters.

If your switch misbehaves

When the wrong branch runs, print the controlling expression just before the switch and compare it with your case values. Mixed-up char and int values, such as '1' (character code 49 in ASCII) against 1, are a frequent cause. When two branches run, check for a missing break. When the compiler reports a duplicate or non-constant case, read the label it points to and check whether the value is truly fixed at compile time. If you are comparing behavior with another language, the JavaScript version has different rules for matching, covered in JavaScript switch statement examples.

Frequently asked questions

Can a switch statement in C use strings?
No. The controlling expression and every case constant must have an integer type (char, signed or unsigned integers, or an enumeration). A string cannot be used as a case label. To branch on a string, compare it with strcmp in an if / else if chain, or map the string to an integer or enum first.
Is default required in a C switch?
No. If no case matches and there is no default label, none of the switch body runs and execution continues after the switch. At most one default label is allowed, and it does not have to be last.
What happens if I forget break in a switch case?
Execution falls through: it continues into the statements of the next label until a break is reached or the switch body ends. This is legal C and sometimes intended, but it is the most common switch bug when it is accidental.
Can two case labels have the same value?
No. Every case constant in one switch must be unique after conversion to the promoted type of the controlling expression, otherwise the code does not compile. A nested switch has its own labels and may reuse values.
Is switch faster than if / else if in C?
The C standard does not say. A compiler is free to turn a switch into a jump table, a binary search or a chain of comparisons, depending on the case values and optimization settings. Choose the form that reads best, and measure if performance matters.

Sources