Assertions in C/C++

Assertions help programmers to test conditions and abort the programs. Mainly used when the code cannot execute further if the condition is not met.

The syntax of assert is

void assert(scalar expression);

Need to include the following header which defined the
assert macro.

#include <assert.h>

Assert prints the error message to standard error
and terminates the program by calling abort(3).

code

assert( val == 0)

output

prog: some_file.c:16: some_func: Assertion `val == 0' failed.

Assertions can be turned off by defining NDEBUG macro. Adding NDEBUG will cause assert not to generate any code to print error and abort.

Recommendation is to not use the NDEBUG macro if using assert to detect error conditions as software may behave non-deterministically.

Source: Assertions in C/C++ – GeeksforGeeks

About the Author

Yogi

24 years of experience in various layers of software. Primarily experienced in system side software design and development on server management software. Interested in linux development in x86 and arm architecture.