標籤:
#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)1111122222demo1.c:7 i<150--assertion failedAborted
//if(0)3333344444
實現了assert宏,和標準庫的同樣功能。可列印出錯的”檔案、行、運算式“。
c,assert 宏的實現