What are assertions in C?

An assertion is a software testing feature built into several programming languages. It checks whether a specific condition is satisfied at a certain point in the code.

Let’s see how it works in C:

#include<stdio.h>
#include <assert.h> // Need to import this library
int main() {
int x = 100;
/*...
... some code here
...
...*/
assert(x == 100); // Throws an error if the expression is false
}

Disabling assertions

When you’re done with testing, assertions can be turned off. This can be achieved by defining an NDEBUG.

#include<stdio.h>
#define NDEBUG // Defining NDEBUG deactivates all the assertions
#include <assert.h>
int main() {
int x = 100;
/*...
... some code here
...
...*/
assert(x == 200); // No error is thrown as all assertions are disabled
}

Where to use assertions

Note that assertions should not be used for error handling. They cannot be used to capture runtime errors. Every runtime error may require a different response. Instead, they are made to respond to program errors. These are usually very trivial things. Two common examples are:

  1. Checking for NULL pointers
  2. Checking for out of bound (or even negative) indices or sizes.

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved