assert() function (assertion function)

assert() function (assertion function)

First, a quick look at the assert function

void assert (int expression);//括号里面是一个表达式。
  1. The assert function is a macro.

  2. If the expression inside the brackets is true, the program executes normally.

  3. If the argument expression of a function-form macro compares equal to zero (that is, the expression is false), a message is written to the standard error device and abort is called, terminating program execution. .

  4. The exact content of the displayed message depends on the particular library implementation, but should at least include: the expression where the assertion failed, the name of the source file, and the line number where the assertion occurred. Common expression formats are:

    A s s e r t i o n f a i l e d : ∗ e x p r e s s i o n ∗ , f i l e ∗ f i l e n a m e ∗ , l i n e ∗ l i n e n u m b e r ∗ Assertion failed: *expression*, file *filename*, line *line number* Assertionfailed:expression,filefilename,linelinenumber

  5. At the beginning of the code, before including **<assert.h>**.

  6. This macro is designed to catch programming errors, not user or runtime errors, because it is usually disabled after the program exits the debugging phase.

Second, clearly show the assert function through code

void EX(int a){
    
    
    assert(a >= 0 && a < 10 );
    if(a % 2){
    
    
        printf("%d",a);
    }
}

int main(){
    
    
    int a;
    
    a = -1;
    EX(a);//表达式为false,触发断言函数,弹出消息框,程序中止。
    
    a = 4 ;
    EX(a);//表达式为true,程序正常执行们不会弹出消息框。
    
}

~~The output result when the expression is false:
output the result if the expression is false

Guess you like

Origin blog.csdn.net/tang20030306/article/details/130002554