As an experienced programmer, the C ++ programming language should not be unfamiliar. Its application can help us easily implement various functional requirements. Here we will give a detailed introduction to some basic applications of the C ++ assert () function.
The assert macro prototype is defined in <assert. h>. Its function is to terminate program execution if its condition returns an error. The prototype definition is as follows:
- #include < assert.h>
- void assert( int expression );
The C ++ assert () function is used to calculate the expression. If its value is false, it is 0. Then it prints an error message to stderr first, then, terminate the program by calling abort. See the following program list badptr. c:
- # Include <stdio. h>
- # Include <assert. h>
- # Include <stdlib. h>
- Int main (void)
- {
- FILE * fp;
- Fp = fopen ("test.txt", "w ");
// Open a file in writable mode. If the file does not exist, create a file with the same name.
- Assert (fp); // so there will be no error
- Fclose (fp );
- Fp = fopen ("noexitfile.txt", "r ");
// Open a file in read-only mode. If the file does not exist, it fails to be opened.
- Assert (fp); // an error occurs here
- Fclose (fp); // the program will never be executed here
- Return 0;
- }
- [Root @ localhost error_process] # gcc badptr. c
- [Root @ localhost error_process] #./a. out
- A. out: badptr. c: 14: main: Assertion 'fp' failed.
Abandoned
The disadvantage of using the C ++ assert () function is that frequent calls will greatly affect program performance and increase additional overhead. After debugging, you can disable the assert call by inserting # define NDEBUG before the # include <assert. h> statement. The sample code is as follows:
- #include < stdio.h>
- #define NDEBUG
- #include < assert.h>
The above is an introduction to the C ++ assert () function.