assert macro(Assert Truth of Expression) in C Language – example and detail

In the C Programming Language, assert is a macro that is designed to be used like a function. It exams the price of an expression that we assume to be authentic underneath ordinary circumstances.

If expression is a nonzero value, the assert macro does nothing. If expression is zero, the assert macro writes a message to stderr and terminates the application via calling abort.


The syntax for the assert macro in the C Language is:

void assert(int expression);

Parameters or Arguments

expression An expression that we assume to be actual beneath normal circumstances.

Required Header

In the C Language, the required header for the assert macro is:

#include <assert.h>

Applies To

In the C Language, the assert macro can be used in the following versions:

ANSI/ISO 9899-1990

assert Example

Let’s appear at an example to see how you would use the assert function in a C program:

/* Example using isxdigit by */

#include <stdio.h>
#include <assert.h>

int main(int argc, const char * argv[])
    /* Define an expression */
    int exp = 1;

    /* Display the value of exp */
    printf("Exp is %d\n", exp);

    /* Assert should not exit in this case since exp is not 0  */

    /* Change expression to 0 */
    exp = 0;

    /* Display the value of exp */
    printf("Exp is %d\n", exp);

    /* In this case exp is 0 so assert will display an error and exit */

    return 0;

When compiled and run, this utility will output:

Exp is 1
Exp is 0
assert: assert.c:24: main: Assertion `exp' failed.
Aborted (core dumped)

See Also

Other C features that are noteworthy when dealing with the assert macro:

abort function <stdlib.h>