C
Beginner
1 min read
if, else, and switch Statements
Example
#include <stdio.h>
#include <stdbool.h> /* bool, true, false (C99) */
const char *day_type(int day)
{
switch (day) {
case 1: /* fall-through intentional */
case 7:
return "weekend";
case 2: case 3: case 4: case 5: case 6:
return "weekday";
default:
return "invalid";
}
}
int main(void)
{
/* if / else if / else */
int temperature = 22;
if (temperature < 0) {
printf("Freezing\n");
} else if (temperature < 10) {
printf("Cold\n");
} else if (temperature < 25) {
printf("Comfortable\n"); /* this branch runs */
} else {
printf("Hot\n");
}
/* switch with fall-through demonstration */
for (int d = 1; d <= 7; d++) {
printf("Day %d is a %s\n", d, day_type(d));
}
/* bool type from <stdbool.h> */
bool is_valid = (temperature >= -50 && temperature <= 60);
if (is_valid) {
printf("Temperature %d is within valid range\n", temperature);
}
return 0;
}