assert() — Verify Condition

Format

#include <assert.h>
void assert(int expression);

Language Level: ANSI

Threadsafe: No.

Description

The assert() function prints a diagnostic message to stderr and aborts the program if expression is false (zero). The diagnostic message has the format:

Assertion failed: expression, file filename, line line-number.

The assert() function takes no action if the expression is true (nonzero).

Use the assert() function to identify program logic errors. Choose an expression that holds true only if the program is operating as you intend. After you have debugged the program, you can use the special no-debug identifier NDEBUG to remove the assert() calls from the program. If you define NDEBUG to any value with a #define directive, the C preprocessor expands all assert calls to void expressions. If you use NDEBUG, you must define it before you include <assert.h> in the program.

Return Value

There is no return value.

Note:
The assert() function is defined as a macro. Do not use the #undef directive with assert().

Example that uses assert()

In this example, the assert() function tests string for a null string and an empty string, and verifies that length is positive before processing these arguments.

#include <stdio.h>
#include <assert.h>
 
void analyze (char *, int);
 
int main(void)
{
   char *string = "ABC";
   int length = 3;
 
   analyze(string, length);
   printf("The string %s is not null or empty, "
          "and has length %d \n", string, length);
}
 
void analyze(char *string, int length)
{
   assert(string != NULL);     /* cannot be NULL */
   assert(*string != '\0');    /* cannot be empty */
   assert(length > 0);         /* must be positive */
}
 
/****************  Output should be similar to  ******************
The string ABC is not null or empty, and has length 3

Related Information



[ Top of Page | Previous Page | Next Page | Contents | Index ]