Page 57 - C-Language
P. 57
will misbehave worse if execution continues. Therefore, it is better to have the assertions
active in production code because if they fire, hell has already broken loose.
• Another option is to use a home-brew system of assertions which always perform the check
but handle errors differently between development (where abort is appropriate) and
production (where an 'unexpected internal error - please contact Technical Support' may be
more appropriate).
static_assert expands to _Static_assert which is a keyword. The condition is checked at compile
time, thus condition must be a constant expression. There is no need for this to be handled
differently between development and production.
Examples
Precondition and Postcondition
One use case for assertion is precondition and postcondition. This can be very useful to maintain
invariant and design by contract. For a example a length is always zero or positive so this function
must return a zero or positive value.
#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);
/* Number of dimensions can not be negative.*/
assert (count >= 0);
/* Calculation */
for (i = 0; i < count; ++i)
{
result = result + (a[i] * a[i]);
}
/* Postcondition: */
/* Resulting length can not 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);
https://riptutorial.com/ 33

