zoukankan      html  css  js  c++  java
  • 头文件<assert.h>

    头文件<assert.h>的目的就是提供宏assert的定义。在程序中可以用这个宏来断言,如果断言是真,则继续执行。如果断言为假,则在标准输入流中输出一条提示信息,并执行终止异常。

    通过宏DEBUG控制断言是否有效:如果程序中包含<assert.h>的地方没有定义NDEBUG,则宏assert为活动形式;如果程序中包含<assert.h>的地方定义了NDEBUG,则宏assert为静止形式。即:

    当存在

    #define NDEBUG

    #include <assert.h>

    时,下面程序中出现的assert(x==y)不执行任何操作

    当存在

    #undef NDEBUG

    #include <assert.h>

    时,下面程序中出现的assert(x==y)不成立时会向输出错误并执行终止异常。

    例1:

    #define NDEBUG  //在取消声明以前的代码段中assert均为静止形式
    #include <assert.h>
    #include <signal.h>
    #include <stdio.h>
    #include <stdlib.h>

    static int val=0;

    static void field_abort(int sig)
    {
    if(val==1)
    {
    puts("SUCCESS TESTING <assert.h>");
    exit(EXIT_SUCCESS);
    }
    else
    {
    puts("FAILURE TESTING <assert.h>");
    exit(EXIT_FAILURE);
    }
    }

    static void dummy()

    {
    int i=0;

    assert(i==0);
    assert(i==1);  //assert为静止形式,故不会发生异常。
    }

    #undef NDEBUG  //取消NDEBUG声明,在define NDEBUG以前assert都是活动形式。
    #include <assert.h>

    int main ()
    {
    assert(signal(SIGABRT,&field_abort)!=SIG_ERR);
    dummy();
    ++val;
    fputs("Sample assertion failure message -- ",stderr);
    assert(val==0);
    puts("FAILURE TESTING <assert.h>");
    return(EXIT_FAILURE);
    }

    执行结果是:

    Sample assertion failure message --
    t: testAssert.c:41: main: Assertion `val==0' failed.
    SUCCESS TESTING <assert.h>

    例2:

    #include <assert.h>  //没有define NDEBUG,故在声明以前assert都是活动形式。
    #include <signal.h>
    #include <stdio.h>
    #include <stdlib.h>

    static int val=0;

    static void field_abort(int sig)
    {
    if(val==1)
    {
    puts("SUCCESS TESTING <assert.h>");
    exit(EXIT_SUCCESS);
    }
    else
    {
    puts("FAILURE TESTING <assert.h>");
    exit(EXIT_FAILURE);
    }
    }

    static void dummy()

    {
    int i=0;

    assert(i==0);
    assert(i==1);  //活动形式,故会终止
    }

    #define NDEBUG
    #include <assert.h>

    int main ()
    {
    assert(signal(SIGABRT,&field_abort)!=SIG_ERR);
    dummy();
    ++val;
    fputs("Sample assertion failure message -- ",stderr);
    assert(val==0);
    puts("FAILURE TESTING <assert.h>");
    return(EXIT_FAILURE);
    }

    执行结果是:

    t: testAssert.c:28: dummy: Assertion `i==1' failed.
    Aborted

  • 相关阅读:
    1.23学习总结:文件流
    vue-router重写push方法,解决相同路径跳转报错,解决点击菜单栏打开外部链接
    手把手教Electron+vue,打包vue项目,打包成桌面程序。
    后台获取的map集合封装json
    VUE同级组件之前方法调用
    字节跳动今日头条-抖音小程序序html富文本显示解决办法
    别总写代码,这130个网站比涨工资都重要
    vue 组件之间的自定义方法互相调用
    swiper轮播图出现疯狂抖动(小程序)
    vue通过地址下载文件
  • 原文地址:https://www.cnblogs.com/Mr-Wenyan/p/7213809.html
Copyright © 2011-2022 走看看