C language assert (assertion) and defensive programming

    Let's take a program for finding factorial as an example, let's understand the role of the assert macro.

    In the following program, the expression in the assert() parentheses cannot be false, so it has no effect on the execution of the program. 

#include<stdio.h>
#include<assert.h>
unsigned long Fact(unsigned int n);
int main()
{
    int m;
    do{
        printf("Input m(m≥0):");
        scanf("%d", &m);
    }while(m<0);//如此书写是为了使得m的值≥0
    //在此加入断言assert(m≥0),
    assert(m>=0);
    //用assert来验证我们写程序时做出的假设: while(m<0) 后m的值不会为负数.
    //如果assert()括号内的表达式为真, assert宏对程序无影响.
    //如果assert()括号内的表达式为假, 它会终止程序的执行, 并报告错误所在的行.
    //不妨将assert宏想象为一个函数, 这样便于理解.
    printf("%d!=%lu\n", m ,Fact(m));
    //
    return 0;
}
unsigned long Fact(unsigned int n)
{
    unsigned int i=2;
    unsigned long result=1;
    while(i<=n)
    {
        result=result*i;
        i++;
    }
    //
    return result;
}

    If the programmer mistakenly writes the expression in the while() parentheses as m>=0 when writing the program, execute the program and see what happens.

#inclu

Guess you like

Origin blog.csdn.net/weixin_42048463/article/details/115266134