typestar

assert and NDEBUG in C

assert documents an invariant and checks it, until NDEBUG removes it entirely.

#include <assert.h>
#include <stddef.h>

int average(const int *values, size_t n) {
    assert(values != NULL);
    assert(n > 0);

    long total = 0;
    for (size_t i = 0; i < n; i++) {
        total += values[i];
    }
    return (int) (total / (long) n);
}

void invariants(void) {
    int values[3] = {1, 2, 3};
    int mean = average(values, 3);
    assert(mean == 2);
    (void) mean;
}

How it works

  1. A failing assert prints the expression and aborts.
  2. Defining NDEBUG compiles every assert away.
  3. So never put a side effect inside one.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
346
Tokens
121
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 73 seconds.

Type this snippet

Step 1 of 2 in Assertions, step 10 of 12 in Preprocessor & headers.

← Previous Next →