Conditionals
Conditionals in C
C provides if/else and switch for branching.
if / else if / else Evaluates conditions sequentially:
c
if (x > 0) { puts("positive"); }
else if (x < 0) { puts("negative"); }
else { puts("zero"); }Any non-zero value is truthy in C; zero is false.
switch / case with fall-through
Unlike many modern languages, C's switch falls through from one case to the next unless you break:
c
switch (day) {
case 1: printf("Mon\n"); break;
case 2: printf("Tue\n"); break;
default: printf("Other\n");
}Fall-through is sometimes intentional — e.g., grouping cases:
c
case 'a':
case 'e':
case 'i': puts("vowel"); break;Ternary operator
c
int max = (a > b) ? a : b;Key points:
- C has no boolean type in C89; use
int(0 = false, non-zero = true). C99 added_Booland<stdbool.h>. - Always include
breakin switch cases unless fall-through is intentional. - switch only works on integer types (int, char, enum).
Code Examples
if/else if/elsec
#include <stdio.h>
int main(void) {
int score = 78;
char grade;
if (score >= 90) grade = 'A';
else if (score >= 80) grade = 'B';
else if (score >= 70) grade = 'C';
else if (score >= 60) grade = 'D';
else grade = 'F';
printf("Score %d -> Grade %c\n", score, grade);
// Ternary
const char *result = (score >= 60) ? "Pass" : "Fail";
printf("%s\n", result);
return 0;
}In C, character literals use single quotes. The ternary operator produces a value and can be used in expressions.
switch with fall-throughc
#include <stdio.h>
int main(void) {
int month = 4;
int days;
switch (month) {
case 1: case 3: case 5: case 7:
case 8: case 10: case 12:
days = 31; break;
case 4: case 6: case 9: case 11:
days = 30; break;
case 2:
days = 28; break;
default:
days = -1;
}
if (days == -1) {
printf("Invalid month\n");
} else {
printf("Month %d has %d days\n", month, days);
}
return 0;
}Multiple case labels with no code between them intentionally fall through, grouping months with the same number of days.
Quick Quiz
1. What is the truth value of 0 in C?
2. What happens in a C switch when you omit `break` from a case?
Was this lesson helpful?