assert() in C

The C assert() function is a macro defined inside the <assert.h> header file. It is a function-like macro that is used for debugging. It takes an expression as a parameter,

  • If the expression evaluates to 1 (true), the program continue to execute.
  • If the expression evaluates to 0 (false), then the expression, source code filename, and line number are sent to the standard error, and then the abort() function is called.

Syntax of assert() in C

void assert(expression);

Parameters

  • expression: It is the condition we want to evaluate.

Return Value

  • The assert() function does not return any value.

If the identifier NDEBUG (“no debug”) is defined with #define NDEBUG then the macro assert does nothing. Common error output is in the form: Assertion failed: expression, file filename, line line-number.

Example: C Program to Illustrate the assert() Function

C




// C Program to demonstrate the use of assert() function
#include <assert.h>
#include <stdio.h>
 
void open_record(char* record_name)
{
    assert(record_name != NULL);
    /* Rest of code */
}
 
int main(void) { open_record(NULL); }


Output

test.c:7: open_record: Assertion `record_name != ((void *)0)' failed.
timeout: the monitored command dumped core
/bin/bash: line 1:    34 Aborted


C exit(), abort() and assert() Functions

The C exit(), abort(), and assert() functions are all used to terminate a C program but each of them works differently from the other. In this article, we will learn about exit, abort, and assert functions and their use in C programming language.

Similar Reads

1. exit() in C

The C exit() function is a standard library function used to terminate the calling process. When exit() is called, any open file descriptors belonging to the process are closed and any children of the process are inherited by process 1, init, and the process parent is sent a SIGCHLD signal....

2. abort() in C

...

3. assert() in C

...

Contact Us