c,assert 宏的实现

预备知识:
#define _VAL(x) #x    //#x的作用就是把x表达式变成一个字符串。(注意 : 不带换行符'\n' , 换行符ascii==10)。
如:_STR(i<100)
printf("%s\n" , _STR(i<100)) ;会在终端打印 i<100。

下面来实现assert宏,和标准库的同样功能,可打印出错的”文件、行、表达式“:
//massert.c
#include "massert.h" #include <stdlib.h> #include <stdio.h> void _mAssert(char * mesg) { fputs(mesg, stderr); fputs("--assertion failed\n", stderr); abort(); }
//massert.h
#ifndef NDEBUG
    extern void _mAssert(char *);
    #define _STR(x)  _VAL(x)
    #define _VAL(x)  #x
    #define massert(test)    \
        ((test)? (void)0 : _mAssert(__FILE__ ":" _STR(__LINE__) " " #test))
#else 
    #define massert(test) 
#endif
//demo1.c
#include "massert.h"

int func1(int i )
{
    massert(i<150);
    return 2*i;    
}
//demo2.c
#define NDEBUG
#include "massert.h"

int func2(int i )
{
    massert(i<150);
    return 2*i;    
}
//demo.c
#include <stdio.h> extern int func2(int i ); extern int func2(int i ); int main() { if(1){ printf("11111\n"); func1(100); printf("22222\n"); func1(200); }else{ printf("33333\n"); func2(100); printf("44444\n"); func2(200); } return 0; }
//终端打印结果:
//if(1)
11111
22222
demo1.c:7 i<150--assertion failed
Aborted
 
  
//if(0)
33333
44444
实现了assert宏,和标准库的同样功能。可打印出错的”文件、行、表达式“。

 

没有系统的时候,怎么实现一个assert?

//massert, 当出现test的情况,报错并返回error_code
#define _STR(x)  _VAL(x)
#define _VAL(x)  #x
#define massert(test, error_code)\
    if((test)){\
        printf("In file "__FILE__ ",Line " _STR(__LINE__) "," #test"\n");\
        return error_code;\
    }

int main()
{
    massert(1>0, 0xff);
    massert(-1>0, 0xff);
    return 0;
}
//In file main.c,Line 13,1>0

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值