[ASNI C] [常用宏定义] [define技巧]

1. 打印变量名及其值

#define Inquire(var, mode)  fprintf(stdout, #var" = "#mode". \n", var)
// Usage
PSTR $PATH$ = "C:\\windows\\system32;."; Inquire($PATH$, "%s");
// Output
// $PATH$ = "c:\windows\system32;.".

2.可变参宏的使用

void _Log(const char *format, ...);
#define Log(format, ...)    _Log(format, ##__VA_ARGS__) //__VA_ARGS__是C99提供的特性可变宏参数,##用于当没有多余参数时删除format之后的','避免编译错误

#include
<stdarg.h> #include <stdio.h> static int i = 0; void _Log(const char *format, ...){   va_list list = 0; // NULL   va_start(list, format);   {     fprintf(stdout, "==Log %d== ", ++i);     vfprintf(stdout, format, list);     fprintf(stdout, "\n");   }   va_end(list); }

3.断言

void _Assert(const char *info, const char *func, int line);
#define Assert(x) if(!(x)) _Assert("断言失败!文件:" __FILE__ ",函数:%s,行:%d--\"" #x "\".", __FUNCTION__, __LINE__)

#include
<stdio.h> void _Assert(const char *info, const char *func, int line){ fprintf(stderr, info, func, line); abort(); }

 

posted @ 2017-11-16 19:10  develon  阅读(204)  评论(1编辑  收藏  举报