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

C Library Macros – assert()

C Library Macros - assert()

C Standard Library - <assert.h> C Standard Library -

Description

C Library Macros void assert(int expression) allows diagnostic information to be written to the standard error file; in other words, it can be used to add diagnostics to a C program.

assert() is a macro in the C standard library, defined in header. It is used to check whether an expression is true at runtime. If the expression is false,assert() the macro outputs an error message and terminates program execution.

assert() is very useful for debugging and testing.

assert() is a powerful tool that helps developers check conditions at runtime and provide detailed error messages when conditions are not met.

Declaration

The following is the declaration of the assert() macro:



#include 

assert(expression);

Parameters

If expression is false (0), assert() outputs an error message containing the following information:

Then the program calls the abort() function to terminate execution.

Return Value

This macro does not return any value.

Example

The following example demonstrates the use of the assert() macro.

Example

#include

<

assert.h

#include

<

stdio.h

int

main

(

)

{

int

a

;

char

str

[

50

]

;

printf

(

"

Please enter an integer value:

"

)

;

scanf

(

"

%d

"

, &

a

)

;

assert

(

a

=

10

)

;

printf

(

"

The integer entered is: %d

\

n

"

,

a

)

;

printf

(

"

Please enter a string:

"

)

;

scanf

(

"

%s

"

,

str

)

;

assert

(

str

!=

NULL

)

;

printf

(

"

The string entered is: %s

\

n

"

,

str

)

;

return

(

0

)

;

}

Let's compile and run the above program in interactive mode, as follows:



请输入一个整数值: 11

输入的整数是: 11

请输入字符串: runoob 

输入的字符串是: runoob 

Disabling assertions

In release builds, you may want to disable assertions to improve performance. This can be done by defining NDEBUG:

#define NDEBUG

#include 

Once NDEBUG is defined, all assert() macros are preprocessed into an empty statement and no checks are performed.

Usage recommendation

Notes

C Standard Library - <assert.h> C Standard Library -