C Library Macro -assert()
C Standard Library - <assert.h>
Description
C Library Macrovoid assert(int expression)Allows diagnostic information to be written to the standard error file; in other words, it can be used to add diagnostics in a C program.
assert()It is a macro in the C standard library, defined in<assert.h>in the header file. It is used at program runtime to check whether an expression is true. 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 program runtime and provide detailed error information when the conditions are not met.
Declaration
Below is the declaration of the assert() macro:
#include <assert.h> assert(expression);
Parameter
- expression-- A condition expression you wish to check; this can be a variable or any C expression. Ifexpressionit is TRUE, assert() performs no action. Ifexpressionit is FALSE, assert() displays an error message on the standard error stream stderr and aborts program execution.
If the value of 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 name
- 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 usage of the assert() macro.
Example
Let's compile and run the above program in interactive mode, as shown below:
请输入一个整数值: 11 输入的整数是: 11 请输入字符串: example 输入的字符串是: example
Disable assertions
In release builds, you may want to disable assertions to improve performance. This can be done by defining NDEBUG:
#define NDEBUG #include <assert.h>
Once NDEBUG is defined, all assert() macros are preprocessed into an empty statement, and no checks are performed.
Usage suggestions
- Debug: In the development and debugging phase, using
assert()It can help you spot logic errors early on. - Documentation: 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()It should not be used to handle predictable runtime errors, but it is an effective means of catching programming errors.
Notes
- Performance: In performance-critical code, assertions may add extra overhead, so they are usually disabled in release builds.
- Error Handling:
assert()It should not be used for handling expected error conditions, but rather for catching programmer errors.