c,assert 宏的实现

预备知识:
#define _VAL(x) #x    //#x的作用就是把x表达式变成一个字符串。(注意 : 不带换行符' ' , 换行符ascii==10)。
如:_STR(i<100)
printf("%s " , _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 ", 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 "); func1(100); printf("22222 "); func1(200); }else{ printf("33333 "); func2(100); printf("44444 "); 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"
");
        return error_code;
    }

int main()
{
    massert(1>0, 0xff);
    massert(-1>0, 0xff);
    return 0;
}
//In file main.c,Line 13,1>0
原文地址:https://www.cnblogs.com/mylinux/p/4211381.html