Assertions (assert)

Exception handling

#include <assert.h>

//assert checks what must always be true in a correct program:
//a false condition prints the condition, the file, the function
//and the line, and abort stops the program
double average(const int numbers[], size_t count) {
    assert(numbers != nullptr);
    assert(count > 0 && "the array must not be empty");
    int sum = 0;
    for (size_t i = 0; i < count; i++) {
        sum += numbers[i];
    }
    return (double)sum / (double)count;
}

int numbers[] = {2, 4, 9};
double result = average(numbers, 3);
//result is 5

//average(numbers, 0); // <- Error, the program stops:
//Assertion failed: count > 0 && "the array must not be empty" (main.c: average:
//8)

//NDEBUG defined before #include <assert.h> (or cc -DNDEBUG
//in a release build) turns every assert into nothing
#ifdef NDEBUG
bool checksOn = false;
#else
bool checksOn = true;
#endif
//checksOn is true

//so a check must not do the work of the program:
//assert(fclose(file) == 0); - without asserts the file stays open

//assert is for mistakes in the code, not for bad input:
//a missing file or a wrong number is handled by a return code

printf("result is %g\n", result);
printf("checksOn is %s\n", checksOn ? "true" : "false");