The **Switch** statement in C is a multi-way branch statement. It allows a variable to be tested for equality against a list of values. Each value is called a **case**, and the variable being switched on is checked for each switch case. It is often a more elegant and readable alternative to a long chain of if...else if statements.
The switch statement evaluates an expression (usually a variable) and compares its value with the values specified in various case labels. When a match is found, the block of code following that case is executed until a break statement is reached.
To use the switch statement effectively, you must understand these three keywords:
else part of an if-else chain.Imagine you want to print the name of the day based on a number (1-7). Using a switch statement makes this very easy to write and read.
When should you use which? Both are used for decision-making, but they have different strengths:
| Feature | Switch Statement | If...Else Statement |
|---|---|---|
| Expression | Must be an integer or character. | Can be any logical expression (range, etc.). |
| Readability | High for multiple discrete values. | Low when there are many else if. |
| Speed | Slightly faster (uses jump tables). | Slightly slower for many conditions. |
To write AdSense-level professional code, keep these C-specific rules in mind:
case x:.float or double value.If you intentionally omit the break statement, the code will continue to execute into the next case. This is sometimes useful for grouping multiple cases together.
default case, even if you think you've covered all possibilities. It acts as a safety net for unexpected input or errors, which is a key part of writing robust, professional software.