C语言之assert(断言)与防御式编程

    我们以一个求阶乘的程序为实例, 一起了解一下assert宏的作用.

    在下面的程序中, assert()括号内的表达式不可能为假, 那么它对程序的执行无任何影响. 

#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;
}

    如果程序员在编写程序时误将while()括号内的表达式写为m>=0, 执行程序, 看一下会发生什么.

#inclu

猜你喜欢

转载自blog.csdn.net/weixin_42048463/article/details/115266134