The following is an introduction to the use of Assert in C language, the need for friends can refer to the next
The stereotype of an Assert macro is defined in <assert.h>, which terminates the execution of the program if its condition returns an error, and the prototype defines:
#include <assert.h>
void assert (int expression);
The function of assert is to calculate the expression expression, if its value is false (that is, 0), then it first prints an error message to stderr.
The program is then terminated by calling abort.
please see the following list of programs BADPTR.C:
Copy Code code 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 a writable manner, and create a file with the same name if it does not exist
assert (FP); So there's no mistake here
Fclose (FP);
fp = fopen ("Noexitfile.txt", "R");//Open a file as read-only and fail to open file if not present
assert (FP); So here's a mistake
fclose (FP); The program will never be executed here.
return 0;
}
Macro Name: Assert
function: Test a condition and possibly terminate the program
Usage: void assert (int test);
Program Example:
Copy Code code as follows:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
struct ITEM {
int key;
int value;
};
/* Add item to list, make sure list are 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 in C.
The stereotype of an Assert macro is defined in <assert.h>, which terminates the execution of the program if its condition returns an error, and the prototype defines:
Copy Code code as follows:
#include <assert.h>
void assert (int expression);
The
assert works by first evaluating the expression expression , and if its value is false (that is, 0), it first prints an error message to the standard error stream stderr . The program is then terminated by calling Abort , otherwise the ASSERT () has no effect. The macro assert () is generally used to confirm the normal operation of the program, where the expression is constructed in a true truth. After debugging, you do not have to remove the ASSERT () statement from the source code because the definition of the macro assert () is null when the macro ndebug is defined.