← Back to C Course | Chapter 4: Control Flow | Lesson 6 of 11

C switch Statement

What is a switch Statement?

A switch statement evaluates one expression once and compares it against a list of case labels, jumping directly to the matching case -- a cleaner alternative to a long else-if ladder when you're comparing one variable against many fixed values.

Example: What is a switch Statement?

c
#include <stdio.h>
int main() {
	int day = 3;
	switch (day) {
		case 3:
			printf("Wednesday");
			break;
	}
	return 0;
}

Day of the Week

Mapping the integers 1 through 7 to day names is a classic switch use case: each case label handles one specific number, making the mapping far more readable than an equivalent chain of if-else comparisons.

Example: Day of the Week

c
#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;
	}
	return 0;
}

Grade Switch

switch can match character constants too, so a grade switch might map the case A to print "Excellent", letting you branch on single-character input just as easily as on integers.

Example: Grade Switch

c
#include <stdio.h>
int main() {
	char grade = 'A';
	switch (grade) {
		case 'A':
			printf("Excellent");
			break;
	}
	return 0;
}

The break Keyword

Without an explicit break at the end of a case block, execution "falls through" and continues running the code in the next case as well -- a frequent source of bugs for anyone coming from a language where fall-through isn't the default.

Example: The break Keyword

c
#include <stdio.h>
int main() {
	int x = 1;
	switch (x) {
		case 1:
			printf("One ");
		case 2:
			printf("Falls through to Two");
			break;
	}
	return 0;
}

The default Case

The default case runs when the switch expression doesn't match any of the listed case values, functioning as a catch-all -- useful for handling unexpected input or flagging invalid values explicitly.

Example: The default Case

c
#include <stdio.h>
int main() {
	int x = 9;
	switch (x) {
		case 1:
			printf("One");
			break;
		default:
			printf("Unknown value");
	}
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.