Skip to content

Choose with if

The Course
•
30 min study

So far every program ran every statement. A report that labels a session needs to choose: a 25-minute block is a focus session, a 10-minute block is a short one, and a duration of zero or less is not a session at all. An if statement runs a block only when a condition holds, and an else if chain picks exactly one label out of several. The order of that chain matters more than it first appears.

Predict and run

Which of the three messages prints for 25? Which branch would print for 24?

Predict before running C
#include <stdio.h>

int main(void) {
    int minutes = 25;
    if (minutes <= 0) {
        printf("Invalid\n");
    } else if (minutes >= 25) {
        printf("Focus\n");
    } else {
        printf("Short\n");
    }
    return 0;
}
Check your prediction
Text
Focus

C checked minutes <= 0 first, found it false, then checked minutes >= 25, found it true, and ran that block. It never looked at the else. Try -1, 0, 24 and 25 and predict each label. The boundary 25 belongs to Focus because the comparison is >=; with > it would belong to Short.

Conditions are numbers

C has no separate true and false values in the way you might expect. A comparison such as minutes >= 25 produces the int 1 when it holds and 0 when it does not. if runs its block when the condition is nonzero and skips it when the condition is zero. The comparison operators are >, >=, == (equal), != (not equal) and their mirror images for "less than" and "at most", written < and <=.

Modern C does have a true/false type, bool from <stdbool.h>, with the values true and false. It is still a small integer underneath, and comparisons still produce int, so this course uses int for conditions.

Print the results of comparisons C
#include <stdio.h>

int main(void) {
    int minutes = 25;
    printf("%d %d %d\n", minutes >= 25, minutes > 25, minutes != 25);
    return 0;
}
Text
1 0 0

The order of an else if chain

A chain is checked from the top, and the first true condition wins. Every later branch is skipped, even if its condition would also be true. That is how you make categories that never overlap, and it is also how a misplaced check hides a bug. Compare this chain with the one you ran above:

The same tests in the wrong order C
#include <stdio.h>

int main(void) {
    int minutes = -5;
    if (minutes < 25) {
        printf("Short\n");
    } else if (minutes <= 0) {
        printf("Invalid\n");
    } else {
        printf("Focus\n");
    }
    return 0;
}
Text
Short

-5 is less than 25, so the first branch claims it and the Invalid branch can never run for any value: every number that is at most 0 is also below 25. The rule to remember is to check invalid values first, then the ordinary categories, from the most specific to the most general.

Assignment is not comparison

= stores a value and == compares two values. Writing one for the other inside a condition is legal C, which is what makes it dangerous:

C
if (minutes = 0) {
    printf("No time logged\n");
}

This stores 0 into minutes and then tests the stored value, 0, which is false. The message never prints, and the original duration is gone. Most compilers warn about an assignment used as a condition, and a local build with this course's flags (-Wall -Wextra -Werror, Day 7) stops there. The browser editor builds without those flags, so here the program simply runs and skips the message. When you see it, you almost always meant ==.

Always use braces

C allows an if without braces, in which case only the next single statement belongs to it. Indentation does not change that:

C
if (minutes <= 0)
    printf("Invalid\n");
    printf("Rejected\n");

Rejected prints for every value, valid or not, because only the first printf is controlled by the if. Compilers can warn about misleading indentation, but the safe habit is to write braces around every branch, even a one-line one. Then adding a second line later cannot silently escape the condition.

Braces keep both lines inside C
#include <stdio.h>

int main(void) {
    int minutes = 30;
    if (minutes <= 0) {
        printf("Invalid\n");
        printf("Rejected\n");
    }
    printf("Checked %d\n", minutes);
    return 0;
}
Text
Checked 30

With braces, both messages belong to the branch, and a valid duration prints only the final line.

Practice

Exercise

Your turn

Classify a quiz score from 0 to 100 into a grade. Scores below 0 or above 100 are Invalid. Otherwise 90 or more is A, 75 or more is B, 60 or more is C, and anything lower is Retry. With score = 75, print:

Text
Score 75: B

Then check the boundaries 101, 100, 90, 89, 60, 59 and -1 by changing the value and predicting each label first.

Your workspace C
#include <stdio.h>

int main(void) {
    int score = 75;
    // Write your solution here.
    return 0;
}
Hint 1: the idea

Check the invalid cases first, then go from the highest grade down. Because the chain stops at the first match, the B branch only needs score >= 75: any score of 90 or more has already been taken.

Hint 2: a first step

Start with two branches for the two invalid ends: one for scores below 0 and one for score > 100, each printing Invalid. Then add the grades from the highest down.

Show one solution
C
#include <stdio.h>

int main(void) {
    int score = 75;
    if (score < 0) {
        printf("Score %d: Invalid\n", score);
    } else if (score > 100) {
        printf("Score %d: Invalid\n", score);
    } else if (score >= 90) {
        printf("Score %d: A\n", score);
    } else if (score >= 75) {
        printf("Score %d: B\n", score);
    } else if (score >= 60) {
        printf("Score %d: C\n", score);
    } else {
        printf("Score %d: Retry\n", score);
    }
    return 0;
}
Text
Score 75: B

Each condition only has to state its lower bound because the earlier branches have already removed everything above it. 90 lands on A and 89 on B because each boundary uses >=. Repeating the Invalid message is clumsy; in the next lesson you will join the two invalid tests into one condition with ||.

Was this article helpful?

Your response is saved on this device.