What is assert() in C?
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.
Library
#include<assert.h>
Declaration
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.
Disabling assert()
We can disable assert() statements by defining the NDEBUG macro before including assert.h in the source file.
Code
1. Without 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.handassert.h.Lines 6-8: We defined an integer variable
xand stored1as its value after that, we defined anassert()with an expression asx==1, which will check thatxis equal to 1 or not.Lines 10-14: We have changed the
xto2after that, we defined anassert()with an expression asx==1, which will check thatxis equal to 1 or not. Because the assert evaluation is false, it will show an error.
2. With 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
NDEBUGnow, this section won't cause any error because assert is disabled.
Free Resources