C Library Macros - assert()
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
- expression -- a conditional expression you wish to check; this can be a variable or any C expression. If expression is TRUE, assert() does nothing. If expression is FALSE, assert() displays an error message on standard error stderr and aborts program execution.
If expression is false (0), assert() outputs an error message containing the following information:
- the text representation of the expression that triggered the assertion failure
- Source File Names
- line number
- function name (if available)
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
- Debugging: during development and debugging, using
assert()can help you detect logic errors early. - Document: Through
assert()can clearly express the programmer's assumptions and expectations about the code, which is very helpful for code maintenance and reading. - Defensive programming: Although
assert()should not be used to handle expected runtime errors, but it is an effective way to catch programming errors.
Notes
- Performance: in performance-critical code, assertions can add extra overhead, so they are usually disabled in release builds.
- Error handling:
assert()should not be used to handle expected error conditions, but rather to catch programmer errors.
C Standard Library -