Precondition and Postcondition
suggest changeOne use case for assertion is precondition and postcondition. This can be very useful to maintain an invariant and design by contract. For example, this function returns a sum of squares, which is zero or positive when the arithmetic does not overflow. Signed overflow in a[i] * a[i] is undefined behavior, so the postcondition does not make a too-large product defined.
#include <stdio.h>
/* Uncomment to disable `assert()` */
/* #define NDEBUG */
#include <assert.h>
int length2 (int *a, int count)
{
int i, result = 0;
/* Precondition: */
/* NULL is an invalid vector */
assert (a != NULL);
/* The number of dimensions cannot be negative. */
assert (count >= 0);
/* Calculation */
for (i = 0; i < count; ++i)
{
result = result + (a[i] * a[i]);
}
/* Postcondition: */
/* The resulting length cannot be negative. */
assert (result >= 0);
return result;
}
#define COUNT 3
int main (void)
{
int a[COUNT] = {1, 2, 3};
int *b = NULL;
int r;
r = length2 (a, COUNT);
printf ("r = %i\n", r);
r = length2 (b, COUNT);
printf ("r = %i\n", r);
return 0;
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents