#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