Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Standard Library –

C Standard Library -

Introduction

The C standard library's assert.hheader file provides a macro named assert , which can be used to verify assumptions made by the program and output a diagnostic message when an assumption is false.

The assert.h standard library is mainly used for making assertions at program runtime. An assertion is a means of testing assumptions, usually used during the debugging phase, so that problems can be detected immediately when the program is in an unexpected state.

The assertion mechanism provided is a useful tool in the C language, helping developers detect and fix errors in a program early on.

Defined macros assert points to another macro NDEBUG, the macro NDEBUG Either part of. If NDEBUG has been defined as a macro name in the source file that includes , then assert the macro is defined as follows:



assert(expression)

The assert macro is used to test whether the expression is true. If the expression is false (i.e., the result is 0), assert outputs an error message and terminates program execution. This error message includes the following:

In release builds, all assert assertions can be disabled by defining NDEBUG. For example:

#define NDEBUG

#include 

Once NDEBUG is defined, the assert macro is preprocessed into an empty statement, with no runtime overhead.

The following is a simple example demonstrating the basic use of assert:

Example

#include

#include

void

test_positive

(

int

x

)

{

   

assert

(

x

0

)

;

}

int

main

(

)

{

   

int

a

=

5

;

   

int

b

=

3

;

    test_positive

(

a

)

;

// This assertion passes

    test_positive

(

b

)

;

// This assertion fails, and the program terminates

   

printf

(

"This line will not be executed if an assertion fails.\n"

)

;

   

return

0

;

}

In the above example, when test_positive(b) is called, since b is a negative number, the assertion x > 0 fails, and the program outputs a message similar to the following and terminates:



Assertion failed: (x > 0), file example.c, line 6

The role of assertions

Notes

Library macros

The following lists the only function defined in the header file assert.h:

No. Function & Description
1 void assert(int expression)
This is actually a macro, not a function, and can be used to add diagnostics to a C program.