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
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:
- The expression that triggered the assertion failure
- Source File Names
- line number
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
- Debugging: During development, assertions can quickly detect logic errors in a program or situations where assumptions do not hold.
- Document: Assertions can serve as part of documentation, describing the preconditions and postconditions of a function.
- Defensive programming: Although it is not recommended to use assertions for parameter checking in production code, in some cases assertions can serve as a last line of defense.
Notes
- Performance: In performance-sensitive code, assertions may add extra overhead, especially when called in large numbers. Therefore, assertions are usually disabled in release builds.
- Error handling: Assertions should not be used to handle error conditions that can be expected and recovered from. Assertions are more for catching programmer errors.
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. |