Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

assertion
c
assert
software testing

What are assertions in C?

Educative Answers Team

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

}
Note that NDEBUG needs to be defined before including assert.h and after including stdio.h

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.

RELATED TAGS

assertion
c
assert
software testing
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring