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 stderrstandard error stream in C/C++ and terminates the program by calling 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.

assert() statements skipped because of NDEBUG

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.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.

2. With NDEBUG

#include <stdio.h>
#define NDEBUG
#include <assert.h>
int main()
{
// Both prints will be executed
// as assert statements are disabled
int 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

Copyright ©2025 Educative, Inc. All rights reserved