
Switch in C
? switch
Statement in C
The switch
statement in C is used to execute one block of code among many options, based on the value of a variable or expression.
? Basic Syntax
#include <stdio.h>int main() { int day = 3; switch(day) { case 1: printf("Monday\n"); break; case 2: printf("Tuesday\n"); break; case 3: printf("Wednesday\n"); break; default: printf("Invalid day\n"); } return 0;}
? Output:
Wednesday
?? Fall-through Example (No break
)
int grade = 2;switch(grade) { case 1: case 2: case 3: printf("Passed\n"); break; case 4: printf("Failed\n"); break;}
? Output:
Passed
? When to Use switch
Use switch
when:
You have many fixed options (like menu choices)
You want cleaner alternatives to long
if...else if
chains