Skip to the task
Layout
Back to classic view

You are looking at lesson 5. Your place is still lesson 8, task 1: Memory.

READTask 2 of 23 · step 2: Contracts and assert

Contracts and assert

The precondition and the postcondition, assert and its message, Release mode, and what doesn't go into an assert.

The contract

A function is an agreement between its author and whoever calls it:

  • the precondition is what the caller must make sure of, e.g. "x is not negative";
  • the postcondition is what the function promises when the precondition holds, e.g. "it returns the nearest whole number".

Write the contract as a comment above the function:

/* Rounds to a whole number.
   Before: x >= 0.
   After: the nearest whole number; x.5 is rounded up. */
int round_to_int(double x) {

The precondition isn't made up: in topic 2 you saw that (int)(x + 0.5) rounds a negative number wrongly.

assert: a precondition the program checks

Nobody checks a comment. assert does:

#include <assert.h>

int round_to_int(double x) {
    assert(x >= 0);
    return (int)(x + 0.5);
}

While the condition is true, assert does nothing. When it is false, the program stops at once and says where. For example, if the program of step 4 called round_to_int(-2.7):

Assertion failed: x >= 0, file C:/.../practice/05/main.c, line 56

Process finished with exit code 3

So the bug is caught where it started, not a hundred lines later, when the wrong number has already spread through the whole program.

assert is for the programmer's mistakes

A user typing 11 is not a bug in the program: you have to expect it, and in topic 3 you asked again with while. assert is for another case: when the code calls a function with something it can't accept, e.g. you forgot to check the grade before print_in_words(11).

What is wrong How to handle it
the user typed an invalid value while and ask again
the code broke a function's precondition assert stops the program

Tests with assert

assert also works for tests: a function that calls your functions with known data and checks the result.

void run_tests(void) {
    assert(round_to_int(0) == 0);
    assert(round_to_int(7.49) == 7);
    assert(round_to_int(7.5) == 8);
}

What to test:

  • the usual case, to see that the function works at all;
  • the edges: 0, 7.49 and 7.5, 1 and 10; bugs hide there most often;
  • both sides of the answer: is_valid(10) and !is_valid(11).

When a test fails, assert prints the line that is false, so you see straight away which case doesn't work.

In Release mode assert is switched off

CMake's Release configuration defines NDEBUG, and then every assert disappears from the program. So never put inside an assert something that has to happen:

assert(read_int("How many? ") > 0);   /* in Release the question is gone */

The course's tests are always compiled with assert switched on.