Switch
statement in C is like a menu in a restaurant. You have a list of items (options), and you can choose one based on what you're in the mood for. Each item is associated with a different dish (code to execute). You give your choice (a value or expression), and the "switch" statement serves the corresponding dish (executes the associated code). If your choice doesn't match any item on the menu, you might get a default dish (code) instead. It's a way to make decisions more efficiently when you have many options to choose from.
Syntax of switch case statement:
Here's the syntax of the switch case statement in C:
switch
(
expression
) {
case
constant1
:
break
;
case
constant2
:
break
;
default
:
}
Here's how it works:
1. The "switch" keyword is followed by a set of parentheses, within which you specify an expression (usually a variable) that you want to evaluate.
2. Inside the "switch" block, you define one or more "case" labels, each followed by a value. When the "expression" matches one of these values, the corresponding code block is executed.
3. If a "case" is matched, the associated code block is executed, and then the "break" statement is used to exit the "switch" block. This prevents the subsequent code blocks from being executed.
4. If none of the "case" labels match the "expression," the "default" case (if present) is executed.
Rules for using the "switch" statement
1.Use a valid expression within the "switch" statement.
2. Define "case" labels with values to match against the expression.
3. End each "case" label with a colon (":").
4. Place executable code under each "case."
5. Use a "break" statement to exit a "case" and prevent fall-through.
6. Include an optional "default" case for unmatched values.
7. Beware of fall-through, where one "case" falls into the next without a "break."
8. Ensure data type consistency between the expression and "case" values.
9. Use unique values for "case" labels within the same "switch" block.
10. If used, position the "default" case at the end of the "switch" block.
Example of Switch case statement in C:
#include
<
stdio.h
>
Copy Code
case
1
:
printf
(
"You chose option 1
"
);
break
;
case
2
:
printf
(
"You chose option 2
"
);
break
;
case
3
:
printf
(
"You chose option 3
"
);
break
;
default
:
printf
(
"Invalid choice
"
);
break
;
}
return
0
;
}
Output :-
You chose option 2