zoukankan      html  css  js  c++  java
  • assert()用法

    assert宏的原型定义在<assert.h>中,其作用是如果它的条件返回错误,则终止程序执行,原型定义:[1]

    #include <assert.h>
    void assert( int expression );

    assert的作用是现计算表达式 expression ,如果其值为假(即为0),那么它先向stderr打印一条出错信息,然后通过调用 abort 来终止程序运行。

    //demo1.c
    #include <stdio.h>
    #include <assert.h>
    #include <stdlib.h>
     
    int demo1(int num)
    {
        assert(num>100);
    
        printf("demo2:%d
    ",num);
        return 0;
    }
    //demo2.c
    #include <stdio.h>
    #include <assert.h>
    #include <stdlib.h>
     
    int demo2(int num)
    {
        assert(num>200);
    
        printf("demo2:%d
    ",num);
        return 0;
    }
    //demo.c
    #include <stdio.h>
    #include <stdlib.h>
     
    int main( void )
    {
        demo1(110);
        demo2(110);//不满足 num>200的条件,报错如下
        return 0;  
    }
    测试现象:
    root@ubuntu:/work/demo# gcc *.c ;./a.out 
    demo2:110
    a.out: demo2.c:7: demo2: Assertion `num>200' failed.
    Aborted

    在调试结束后,可以通过在包含#include <assert.h>的语句之前插入 #define NDEBUG 来禁用assert调用,示例代码如下:

    #include <stdio.h>
    #define NDEBUG
    #include <assert.h>

    如:

    //demo2.c
    #include <stdio.h> #define NDEBUG //仅对本文件起作用 #include <assert.h> #include <stdlib.h> int demo2(int num) { assert(num>200);//未编译展开宏。 printf("demo2:%d ",num); return 0; }
    现象:
    root@ubuntu:/work/demo# gcc *.c ;./a.out 
    demo2:110
    demo2:110

    参考:

    1. assert()函数用法总结
    http://www.cnblogs.com/ggzss/archive/2011/08/18/2145017.html

  • 相关阅读:
    MYSQL学习笔记——sql语句优化工具
    SQL优化工具SQLAdvisor使用
    SqlServer性能检测和优化工具使用详细
    Sql优化器究竟帮你做了哪些工作
    通俗易懂的php多线程解决方案
    PHP删除数组中空值的方法介绍
    PHP函数
    python函数回顾:dir()
    面向对象封装思想小结
    python函数回顾:all()
  • 原文地址:https://www.cnblogs.com/mylinux/p/4151610.html
Copyright © 2011-2022 走看看