The following describes how to use assert in C language. For more information, see
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 );
Assert is used to calculate the expression. If its value is false (that is, 0), It prints an error message to stderr first,
Then, terminate the program by calling abort.
See the following program list badptr. c:
Copy codeThe Code is as follows:
# 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 it 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 it does not exist, the file fails to be opened.
Assert (fp); // an error occurs here
Fclose (fp); // the program will never be executed here
Return 0;
}
Macro name: assert
Skill: test a condition and possibly terminate the program
Usage: void assert (int test );
Program example:
Copy codeThe Code is as follows:
# Include <assert. h>
# Include <stdio. h>
# Include <stdlib. h>
Struct ITEM {
Int key;
Int value;
};
/* Add item to list, make sure list is not null */
Void additem (struct ITEM * itemptr ){
Assert (itemptr! = NULL );
/* Add item to list */
}
Int main (void)
{
Additem (NULL );
Return 0;
}
Assert () macro usage
Note: assert is a macro, not a function. In the assert. h header file of C.
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:
Copy codeThe Code is as follows:
# Include <assert. h>
Void assert (int expression );
Assert is used to calculate the expression first.Expression, If its value is false (that is, 0), it first streams to the standard errorStderrPrint an error message and callAbortOtherwise, assert () does not work. Macro assert () is generally used to confirm the normal operation of the program, where the expression construction is true only when no error occurs. After debugging, you do not need to delete the assert () Statement from the source code, because the macro assert () definition is empty when NDEBUG is defined.