Switch statement in C
The switch statement is a multiple-selection control statement in C. It enables your software to select several actions according to an expression’s value. When you need to test a variable or expression against a set of constant integral values, it can be used as an alternative to a lengthy chain of if-else if statements.
The switch statement’s general form, or syntax, is as follows:
switch (expression) {
case constant1:
// Statements to execute if expression == constant1
// ...
break; // Optional, but usually included
case constant2:
// Statements to execute if expression == constant2
// ...
break; // Optional
// ... more cases
case constantN:
// Statements to execute if expression == constantN
// ...
break; // Optional
default: // Optional
// Statements to execute if no case matches
// ...
// break; // Optional, often omitted if default is last
}
// Program continues here after switch
The switch statement functions as follows:
- After the switch keyword, the expression enclosed in parenthesis is evaluated.
- Then, one by one, the expression’s value is contrasted with the constant values linked to each case label.
- Execution leaps to the statement or statements that follow that matching case label if the value of the expression matches a case constant.
- Execution advances to the statements that follow the default label if, after examining every case label, no match is discovered and a default label is present.
- If there is no default label and no match, the switch statement does nothing, and program control moves on to the statement that comes right after the switch’s closing brace }.
Important details regarding the C switch statement:
- The expression that the switch evaluates needs to be integral in nature. This covers the types int, char, long, and enum. Types with floating points (float, double) are prohibited.
- A constant integral expression must come after the case labels. This implies that at compilation time, the value must be known. Variables and ranges (such as case i <= 20:) cannot be used in case labels.
- In a single switch statement, every case constant value needs to be distinct.
- It is optional to use the default case. All values that don’t fit any of the particular case labels are handled by it. Although it might appear anywhere, it is usually towards the conclusion. It’s a good idea to include a default to deal with unexpected values.
- At the conclusion of each case’s statements, the break statement is frequently used. Its function is to end the switch statement once the code for the corresponding case has been run. The statement that comes just after the switch block gains program control.
- Execution will “fall through” to the following case if there is no break statement, carrying out the statements in succeeding cases until a break occurs or the switch’s end is reached. Although this “fallthrough” is a feature, if it is not used purposefully, it may result in logical problems. It’s best practice to provide a note if fallthrough is planned.
- Just listing the case labels one after the other before the statements allows them to share a block of code.
- For every case, you can have one or more statements. Unlike if and else, braces {} are not needed around numerous statements in a case.
When working with a lot of specialized numeric or character comparisons, the switch statement is frequently easier to read and occasionally more effective than a complicated if-else if-else ladder. It is very helpful when making programs that are menu-driven.
You can also read What Is The Basic Input And Output Function In C Language?
An example of switch statement code that checks a character for a fruit is as follows:
Both uppercase and lowercase input are handled by this program, which also has a default case for other inputs. It asks the user to enter a character and utilises a switch statement to determine if it matches the initial letter of “Apple,” “Banana,” or “Cherry.”
#include <stdio.h>
#include <ctype.h> // Required for toupper()
int main() {
char choice;
printf("Enter the first letter of a fruit (A, B, or C): ");
// Use scanf to read a character
scanf(" %c", &choice); // Note the space before %c to consume potential whitespace
// Convert the input character to uppercase to handle both cases easily
choice = toupper(choice); // toupper()
// Use a switch statement to check the character
switch (choice) {
case 'A': // Case label for 'A'
printf("You chose Apple!\n"); // Statements for this case
break; // Exit the switch after this case
case 'B': // Case label for 'B'
printf("You chose Banana!\n");
break; // Exit the switch
case 'C': // Case label for 'C'
printf("You chose Cherry!\n");
break; // Exit the switch
default: // Optional default case if no other case matches
printf("Invalid option entered.\n"); // Statements for the default case
// break; // break is often omitted in the last case (like default) as control exits naturally
}
printf("Program finished.\n"); // This line is executed after the switch
return 0; // Indicate successful execution
}