C switch statement
Created By: chatGPT
The switch statement in C is used for multi-way branch selection. It evaluates an expression and executes the corresponding case block that matches the expression's value. It can be much clearer than using multiple if-else statements, especially when checking the same variable against different values.
switch (expression) {
case constant1:
// Code block for constant1
break;
case constant2:
// Code block for constant2
break;
default:
// Code block if no case matches
}
Here's a simple example of a switch statement that evaluates the day of the week. Based on the value provided, it outputs the corresponding name of the day.
int day = 3;
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:
printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default:
printf("Invalid day\n");
}
In this example, if the value of
day
is 3
, the output will be Wednesday. Notice the use of break
, which is crucial. If we omit the break
statement, execution will continue into the subsequent case until a break is encountered or the switch finishes. This behavior is called fall-through.int day = 2;
switch (day) {
case 1:
printf("Day 1\n");
case 2:
printf("Day 2\n");
case 3:
printf("Day 3\n");
}
// Output:
// Day 2
// Day 3
You can also use arithmetic or string comparisons in switch cases. However, each case must be a unique constant. Strings cannot be directly used in switch statements in C, but they can be compared using
if-else
or by using a separate enumeration or integer representation.#include <stdio.h>
int main() {
char grade = 'B';
switch (grade) {
case 'A':
printf("Excellent!\n");
break;
case 'B':
printf("Well done!\n");
break;
case 'C':
printf("Good job!\n");
break;
default:
printf("Grade not recognized\n");
}
return 0;
}