assert() is a macro (used as a function) in C. assert() statements help to verify the assumptions made by the developer. They are useful when debugging a program.
#include<assert.h>
The following is the declaration of assert():
void assert(int exp)
exp: The expression to be evaluated as non-zero (true) or zero (false).
If exp evaluates to zero, assert() sends the error message to
abort(). On the other hand, normal execution continues if exp evaluates to non-zero.
assert()We can disable assert() statements by defining the NDEBUG macro before including assert.h in the source file.
NDEBUG#include <stdio.h>#include <assert.h>int main(){int x = 1;assert(x == 1);printf("First assert passed");x = 2;assert(x == 1);// The below line is not printed// because assert evaluates to false.printf("\nSecond assert passed");return 0;}
Lines 1&2: Included necessary header files stdio.h and assert.h .
Lines 6-8: We defined an integer variable x and stored 1 as its value after that, we defined an assert() with an expression as x==1, which will check that x is equal to 1 or not.
Lines 10-14: We have changed the x to 2 after that, we defined an assert() with an expression as x==1, which will check that x is equal to 1 or not. Because the assert evaluation is false, it will show an error.
NDEBUG#include <stdio.h>#define NDEBUG#include <assert.h>int main(){// Both prints will be executed// as assert statements are disabledint x = 1;assert(x == 1);printf("First assert passed");x = 2;assert(x == 1);printf("\nSecond assert passed");return 0;}
Line 2: We have included NDEBUG, which will disable the assertion of the code.
Lines 13-15: Because we are using NDEBUG now, this section won't cause any error because assert is disabled.
Free Resources