Background:
The switch statement was introduced in C to facilitate the distribution of control across several branches depending on the value of an expression. It serves as an alternative to a large chain of if-else statements and is widely used for handling commands, states, and enumeration values.
Problem:
The main dangers of the switch statement relate to forgotten break statements, unexpected fallthrough, difficulties with variables declared within a block, and the requirement that the expression type must be integral.
Solution:
For safe use:
break (or explicitly mark the necessity for fallthrough with comments);int or compatible types;case in the default branch;case constructs, or in nested {} scopes.Example code:
#include <stdio.h> void print_day(int day) { switch (day) { case 1: printf("Monday\n"); break; case 2: printf("Tuesday\n"); break; case 3: printf("Wednesday\n"); break; case 4: printf("Thursday\n"); break; case 5: printf("Friday\n"); break; case 6: case 7: printf("Weekend\n"); break; default: printf("Unknown day\n"); } }
Key features:
Can you use the float type in a switch expression?
No. The C standard requires that the expression in a switch be integral or converted to an integer (char, short, int, long, enum, etc.).
What happens if you change the order of the cases — does order affect logic?
The order of case declarations in a switch does not affect the search for the target value. The code executes starting from the matching case until the first break. However, the order does matter in the absence of a break (fallthrough).
Can you declare variables inside a case without curly braces?
No. Declaring a variable after a case without an additional {} block will lead to a compilation error. Correct:
switch (x) { case 1: { int y = 0; break; } }
In a large project, a programmer forgot a break after one of the cases and ended up executing several branches in sequence erroneously. The bug was noticed only by the user.
Pros:
Cons:
In cases where fallthrough was necessary, commented fallthroughs were used with explanations, all critical cases were accompanied by break or return, and warnings were printed in default.
Pros:
Cons: