Assert in C Programming
Asserts are used in programs if the developer wishes to assert or make assumptions. An example where we can use assert is to check whether the pointer that is returned by malloc() is a NULL value or not. It is a diagnostic tool.
The Syntax for assert() function in C Programming
It takes an expression for the parameter in the function. The parameter is evaluated. If the value returned after evaluation of the expression is 0 or FALSE, it returns the expression along with the file name and line of execution as an error. If the errors occur, the program calls the abort() function. The assert function does not do anything if the expression is evaluated TRUE.
Implementing assert() in a Program
To implement the assert() function in your program, you must include assert.h header file in your program.
In the program below, an assertion is made since the condition is false. The assertions fail.
Assert vs Error Handling in C Programming
The programmer uses assertions to check the logically incorrect conditions. It is used in those scenarios where the programmers want to ensure the state of the code before running or completing the execution of the program. Such situations can't happen logically.
Error handling is performed during the runtime, whereas the asserts statement does not run during the run time. It is advised to not use the assert() statement in your program while execution as it may cause side effects during the execution.
Ignore the Assertions in your Program
As discussed, the assert statement may cause side effects during the compile time of the program and removing all the assertions from the code is a very tedious and difficult process.
In C programming language, there is an easier method that completely removes all the assert statements from your code during the execution.
It is done using the preprocessor NDEBUG.
Below is the code implementing assert while using the NDEBUG.