When should we use asserts in C?

assert aborts the process, but is turned into a no-op when the program is compiled with -DNDEBUG, so it’s a rather crude debugging tool and nothing more than that. You should only use assert to check for situations that “can’t happen”, e.g. that violate the invariants or postconditions of an algorithm, but probably not for input validation (certainly not in libraries). When detecting invalid input from clients, be friendly and return an error code.

An example use of assert could be: you’ve implemented an incredibly smart sorting algorithm and you want to check whether it really sorts. Since the sorting function is supposed to “just work” and therefore doesn’t return a value, you can’t add error returns without changing the API.

void sort(int *a, size_t n)
    recursive_super_duper_sort(a, 0, n);
    assert(is_sorted(a, n));

static bool is_sorted(int const *a, size_t n)
    for (size_t i=0; i<n-1; i++)
        if (a[i] > a[i+1])
            return false;

    return true;

In the long run, you’d really want a proper unit testing framework for this kind of thing instead of assert, but it’s useful as a temporary debugging tool.

Leave a Comment