Learn C · lesson 13 of 60 · about 7 minutes
if and else
Let the report act on what it found: run code only when a condition is true, give an alternative with else, and keep every branch in braces.
What you'll learn
- Write an if statement
- Add an else branch
- Use braces for every branch
Doing something about it
Your report knows whether the backup can run, and can_backup holds the answer, but nothing happens yet. if (condition) { ... } runs its block only when the condition is true, and else { ... } runs otherwise. The condition goes in round brackets, and each block goes in braces.
The backup runs, or it doesn't
#include <stdio.h>
#include <stdbool.h>
int main(void) {
bool can_backup = true;
int used = 2560;
int backup = 1000;
if (can_backup) {
used += backup;
printf("Backup done. Used: %d KiB\n", used);
} else {
printf("Backup skipped\n");
}
printf("Report finished\n");
return 0;
}Output
Backup done. Used: 3560 KiB
Report finishedAlways use braces
Without braces, an if only guards the one statement after it. Indenting a second line doesn't put it inside: C ignores indentation. Worse, an else after two unbraced lines doesn't compile at all, because the if already ended. Braces on every branch avoid both problems, even when a branch is one line long.
Tip
In a condition, 0 counts as false and any other number as true, so if (warnings) runs its block whenever there's at least one warning.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.