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
- A failing assert prints the expression and aborts.
- Defining
NDEBUGcompiles every assert away. - So never put a side effect inside one.
Keywords and builtins used here
NULLaverageconstforintinvariantslongreturnsize_tvoid
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.
Step 1 of 2 in Assertions, step 10 of 12 in Preprocessor & headers.