In C, a switch statement is a control flow statement that allows a variable or expression to be tested against a series of values (called cases). It helps simplify multiple if-else conditions when checking for multiple possible values of a single variable.
Syntax:
switch (expression) {
case value1:
// Code to execute if expression == value1
break;
case value2:
// Code to execute if expression == value2
break;
// More cases...
default:
// Code to execute if no case matches
}
Key Points:
- switch checks the value of the expression.
- Each case corresponds to a possible value of the expression.
- The break statement ends the switch block after a matching case is found.
- The default case runs if none of the cases match the expression.
Example 1:
#include <stdio.h>
int main() {
int day = 2;
switch (day)
{
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
default:
printf("Invalid day");
break;
}
return 0;
}
Output:
Tuesday
Example 2:
#include <stdio.h>
int main() {
enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
// Initialize today as Friday
enum Day today = Friday;
switch (today) {
case Monday:
printf("Start of the work week!");
break;
case Friday:
printf("End of the work week!");
break;
default:
printf("It's a regular day.");
break;
}
return 0;
}
Output:
End of the work week!
C switch statement – Interview Questions
Q 1: What is the switch statement in C?
Ans: It executes code based on the value of an expression.
Q 2: Which data types are allowed in switch?
Ans: Integer and character types.
Q 3: Why is break used in a switch?
Ans: To prevent execution from falling through to the next case.
Q 4: What is the default case?
Ans: It runs when no case matches the expression.
Q 5: Can a switch work without break?
Ans: Yes, but it causes fall-through behavior.
C Switch Statement – Objective Questions (MCQs)
Q1. Which of the following can be used in a switch statement?
Q2. What is the purpose of the break statement in a switch block?
Q3. What happens if the break statement is missing in a switch case?
Q4. Which keyword is used to specify a block that executes when no case matches?
Q5. What is the output of this code?
int x = 2;
switch (x) {
case 1: printf("One");
case 2: printf("Two");
case 3: printf("Three");}