Skip to main content

Break and default in switch

Explain importance of break and default statements in switch statements.

  • break: ends the switch after a case is executed, so control leaves the switch. Without it, execution falls through into the next cases, running them too, even though their values do not match.
  • default: the block executed when none of the case values matches the expression. It handles invalid or unexpected values, and acts like the final else. It is optional, and is usually written last.
#include <stdio.h>
int main(void)
{
    int n = 2;
    printf("Without break:\n");
    switch (n)
    {
        case 1: printf("One\n");
        case 2: printf("Two\n");
        case 3: printf("Three\n");
        default: printf("Default\n");
    }
    printf("With break and default:\n");
    switch (n + 5)
    {
        case 1: printf("One\n");   break;
        case 2: printf("Two\n");   break;
        default: printf("No match\n");
    }
    return 0;
}

Output:

Without break:
Two
Three
Default
With break and default:
No match

In the first switch (n = 2) there is no break, so "Two", "Three" and "Default" are all printed. In the second, no case matches 7, so default prints "No match".

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 5 questions →