C If Else
Booleans gave the program true and false. An if statement runs its block only when a check is true, and an else statement runs a different block when the check is false.
A check that is true
This program sets sunny to true. The if block runs because the check is true.
#include <stdio.h>
#include <stdbool.h>
int main() {
bool sunny = true;
if (sunny) {
printf("It is sunny.\n");
}
return 0;
}The else block
This program sets hungry to false. The if block is skipped, so the else block runs.
#include <stdio.h>
#include <stdbool.h>
int main() {
bool hungry = false;
if (hungry) {
printf("Eat lunch.\n");
} else {
printf("Not hungry yet.\n");
}
return 0;
}A chain of checks
This program checks hot first, then cold. The cold check is true, so its block runs.
#include <stdio.h>
#include <stdbool.h>
int main() {
bool hot = false;
bool cold = true;
if (hot) {
printf("Drink water.\n");
} else if (cold) {
printf("Wear a coat.\n");
} else {
printf("Just right.\n");
}
return 0;
}Example
#include <stdio.h>
#include <stdbool.h>
int main() {
bool raining = true;
bool windy = false;
if (raining) {
printf("Take an umbrella.\n");
} else if (windy) {
printf("Hold your hat.\n");
} else {
printf("Enjoy the day.\n");
}
return 0;
}Key points
- An if statement starts with the word if and a check in round brackets.
- The check uses a bool variable, like sunny or hungry.
- The code to run sits inside curly braces after the check.
- An else statement follows an if statement and runs when the check is false.
- An else if statement adds a second check after the first check.
- Only one block runs: the first check that is true, or the else block.
- Each check is a bool value, true or false.
raining is true and windy is false. The first check is true, so its block runs, and the later checks are skipped.
Note
An else always belongs to the if just before it.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What happens when the check in an if statement is false and there is no else?