what is assert in C?

2024-10-15

assert is a macro no a function. It can be used in:

  • test unit
  • verify the program status when initializing
  • verify the program runing logic is right or wrong

If the asserted condition is false. The program will exit unexpectedly. Hence, we should not misunderstand the assert error handling and normal error handling. In many situations, we should use normal error handling rather than assertion.

Now, I show you an example how to use an assert macro.

#define NDEBUG
#include <cassert>

int main(void) {
    assert(1 != 1);
}

This example will panic, since the assertion is false.