Implementation of C,ASSERT macro

Source: Internet
Author: User

#define _VAL (x)                #x//#x的作用就是把x表达式变成一个字符串. (Note: no newline characters ' \ n ', line break ascii==10).
such as: _str (i<100)
printf ("%s\n", _str (i<100)); i<100 is printed on the terminal.

Here's how to implement the Assert macro, and the same functionality as the standard library. You can print the file, line, and expression of the error.
// massert.c
" massert.h " <stdlib.h><stdio.h>void _massert (char * mesg) { Fputs (MESG, stderr); Fputs ("--assertion failed\n", stderr); Abort ();}
//massert.h#ifndef Ndebugextern void_massert (Char*); #define_STR (x) _val (x)#define_val (x) #x#defineMassert (test) \(test)? (void)0: _massert (__file__":"_str (__line__)" "#test))#else     #defineMassert (Test)#endif
// demo1.c  "massert.h"int func1 (int  i) {    Massert (i <);     return 2*i;    }
// demo2.c #define Ndebug"massert.h"int func2 (int  i) {    Massert (i <);     return 2*i;    }
Demo.c
#include <stdio.h>extern intFunc2 (inti);extern intFunc2 (inti);intMain () {if(1) {printf ("11111\n"); Func1 ( -); printf ("22222\n"); Func1 ( $); }Else{printf ("33333\n"); Func2 ( -); printf ("44444\n"); Func2 ( $); } return 0;}
Terminal Printing results:
// if (1) 11111 22222 demo1.c: 7 i<--assertion failedaborted
// if (0) 33333 44444
The Assert macro is implemented with the same functionality as the standard library. You can print the file, line, and expression of the error.

Implementation of C,ASSERT macro

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.