Function name : assert
Header file : <assert.h>
Function prototype : void assert(int expression);
Function : Assert whether an expression is correct
Parameter : expression If its value is false (that is, 0), then it first prints an error message to stderr, and then terminates the program by calling abort.
Return value : No return value
Replenish :
1. Frequent calls will greatly affect the performance of the program and increase additional overhead. After debugging, you can disable assert calls by inserting #define NDEBUG before the statement containing #include <assert.h>.
2. Check the legality of the parameters passed in at the beginning of the function.
3. Each assert only tests one condition, because when multiple conditions are tested at the same time, if the assertion fails, it is impossible to intuitively determine which condition failed.
4. You cannot use statements that change the environment, because assert only takes effect in DEBUG. If you do this, you will encounter problems when the program ignores the assert statement when it is actually running, such as:
mistake:
assert(i++<100);
This is because if an error occurs, for example, i=100 before execution, then this statement will not be executed, and then the i++ command will not be executed.
correct:
assert(i<100);i++;
5. There should be a blank line between assert and the following statements to create a sense of logical and visual consistency.
6. In some places, assert cannot replace conditional filtering. Assert is used to avoid obvious errors, not to handle exceptions. Errors and exceptions are different. Errors should not occur, and exceptions are inevitable. C language exceptions can be handled through conditional judgment, and other languages have their own exception handling mechanisms. A very simple rule for using assert is to use it at the beginning of a method or function. If you use it in the middle of a method, you need to carefully consider whether it is appropriate. A functional process has not started at the beginning of the method, and problems that occur during the execution of a functional process are almost all exceptions.
Program example : Assert variable a<80 and output the result
#include<assert.h>#include<stdio.h>intmain(void){inta=50;assert(a<80);//Assert a<80, if it is 0, output an error message and terminate the program, otherwise continue to execute printf (Assertaistruen);return(0);}
Running results:
Assertaistrue