c,assert 宏的實現

來源:互聯網
上載者:User

標籤:

#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 宏的實現

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.