Tutorial by Examples

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()`...
An assertion is a statement used to assert that a fact must be true when that line of code is reached. Assertions are useful for ensuring that expected conditions are met. When the condition passed to an assertion is true, there is no action. The behavior on false conditions depends on compiler fl...
C11 Static assertions are used to check if a condition is true when the code is compiled. If it isn't, the compiler is required to issue an error message and stop the compiling process. A static assertion is one that is checked at compile time, not run time. The condition must be a constant expres...
During development, when certain code paths must be prevented from the reach of control flow, you may use assert(0) to indicate that such a condition is erroneous: switch (color) { case COLOR_RED: case COLOR_GREEN: case COLOR_BLUE: break; default: assert(0); ...
A trick exists that can display an error message along with an assertion. Normally, you would write code like this void f(void *p) { assert(p != NULL); /* more code */ } If the assertion failed, an error message would resemble Assertion failed: p != NULL, file main.c, line 5 Ho...

Page 1 of 1