Skip to content

Checks That Fail Loudly

The Course
•
30 min study

Checking a function by running it and reading the output works once. It does not work the tenth time you change the code, because you will not reread every line of output, and a wrong 0 looks a lot like a right 0. A better check states the expected answer in the code and stops the program the moment the answer is wrong. assert from <assert.h> does exactly that. A set of assertions becomes a small test program you can rerun after every change, and it only prints a success message when every promise held.

Predict and run

Will this program reach the printf?

Predict before running C
#include <stdio.h>
#include <assert.h>

int valid_minutes(int minutes) {
    return minutes >= 1 && minutes <= 180;
}

int main(void) {
    assert(valid_minutes(1));
    assert(valid_minutes(180));
    assert(!valid_minutes(0));
    assert(!valid_minutes(181));
    printf("Checks passed\n");
    return 0;
}
Check your prediction
Text
Checks passed

All four expressions were true, so execution continued past each assert and printed the message. Now change minutes >= 1 to minutes > 1 and run again. The program stops at the first assertion, valid_minutes(1), and the success line never prints. Restore the original before you continue.

What a failed assertion does

assert(expression) evaluates the expression. If it is nonzero, nothing happens. If it is zero, the program prints a diagnostic to the error stream and ends abnormally, with a failing exit status. The text varies between systems, but it names the file, the line, the function and the expression:

Shell
main.c:9: main: Assertion `valid_minutes(1)' failed.
Aborted

Do not write tests that compare this text; it differs between compilers and platforms. What matters is that the run fails, and that the failing line tells you which promise broke.

Choose cases that could catch a bug

A test is only useful if a plausible mistake would make it fail. assert(valid_minutes(90)) passes for the correct rule, but it also passes for > 1, for >= 0, for an upper limit of 179 and for a function that returns 1 for everything. Values in the middle of a range prove very little.

The strongest cases sit on the edges. For the rule "1 through 180":

  • 1 and 180 must be accepted. They catch > written where >= was meant, and the same slip at the top.
  • 0 and 181 must be rejected. They catch a range that is one too wide, and a function that accepts everything.

Work out each expected value yourself, from the rule as written, before you look at what the function returns. If you copy the function's output into the assertion, you are only testing that the function agrees with itself.

Assertions check programmers, not users

assert is for conditions that should be impossible if the program is correct. It is not a way to reject bad input. A build can define the macro NDEBUG, and then every assert is removed from the program entirely. Input validation must survive that, so it uses ordinary if statements that print a message or return a failure.

That removal has a second consequence: never put work that must happen inside an assert.

C
assert(count_session(&count));

With NDEBUG defined, the whole line disappears and the session is never counted. Do the work in its own statement and assert on the result:

Work first, then assert C
#include <stdio.h>
#include <assert.h>

int add_minutes(int total, int minutes) {
    return total + minutes;
}

int main(void) {
    int total = add_minutes(20, 15);
    assert(total == 35);
    total = add_minutes(total, 0);
    assert(total == 35);
    printf("Total: %d\n", total);
    return 0;
}
Text
Total: 35

Each calculation happens in a normal statement, so the program behaves the same with or without assertions. Never define NDEBUG while you are testing in this course.

Practice

Exercise

Your turn

Write int focus_level(int minutes). It returns 0 for an invalid duration (outside 1 through 180), 1 for a short session (below 25 minutes) and 2 for a focus session (25 minutes or more). Write one assertion for each of the six boundary values 0, 1, 24, 25, 180 and 181, then print:

Text
Focus checks passed
Your workspace C
#include <stdio.h>
#include <assert.h>

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

There are three boundaries: 1, 25 and 180. Each one needs the value on both sides. Write the six expected results on paper from the rule before writing the function.

Hint 2: a first step

Write the assertions first, with an empty function that returns 0. Run it, watch the first failure, then fill in the function until every assertion passes.

Show one solution
C
#include <stdio.h>
#include <assert.h>

int focus_level(int minutes) {
    if (minutes < 1 || minutes > 180) {
        return 0;
    }
    if (minutes < 25) {
        return 1;
    }
    return 2;
}

int main(void) {
    assert(focus_level(0) == 0);
    assert(focus_level(1) == 1);
    assert(focus_level(24) == 1);
    assert(focus_level(25) == 2);
    assert(focus_level(180) == 2);
    assert(focus_level(181) == 0);
    printf("Focus checks passed\n");
    return 0;
}
Text
Focus checks passed

Each pair of assertions pins one boundary from both sides, so moving any boundary by one breaks a check. Try it: change minutes < 25 to minutes <= 25 and the assertion for 25 fails. Writing the assertions before the function, and watching them fail first, proves they can fail at all. The checkpoint asks you to do this for a rule of your own.

Was this article helpful?

Your response is saved on this device.