totn C Functions

C Language: assert macro
(Assert Truth of Expression)

In the C Programming Language, assert is a macro that is designed to be used like a function. It checks the value of an expression that we expect to be true under normal 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 program by calling abort.

Syntax

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

void assert(int expression);

Parameters or Arguments

expression
An expression that we expect to be true under 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 look at an example to see how you would use the assert function in a C program:

/* Example using isxdigit by TechOnTheNet.com */

#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  */
    assert(exp);

    /* 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 */
    assert(exp);

    return 0;
}

When compiled and run, this application will output:

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

See Also

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