经典代码-C宏 #转字符串【瓦特芯 笔记】

在调试C语言程序时,有时需要打印宏的名字。可以通过定义宏,宏名字的数组来获得。

例如:

  1. #include <stdio.h>
  2. #define MACRO_STR(x) {x, #x}
  3. typedef struct _macro_str { 
  4. int id; 
  5. char *name; 
  6. }MACRO_STR_T; 
  7. typedef enum _color{ 
  8.     RED, 
  9.     GREEN, 
  10.     BLUE, 
  11. }COLOR; 
  12. MACRO_STR_T g_color_str[] ={ 
  13.     MACRO_STR(RED),  
  14.     MACRO_STR(GREEN), 
  15.     MACRO_STR(BLUE), 
  16.     {-1, NULL} 
  17. }; 
  18. static const char * get_macro_name(MACRO_STR_T* table, int id) 
  19. int i = 0; 
  20. while(table[i].id != -1 && table[i].name != NULL){ 
  21. if(table[i].id == id) 
  22. return table[i].name; 
  23.         i++; 
  24.     } 
  25. return ""; 
  26. static const char * get_color_name(COLOR color) 
  27. return get_macro_name(g_color_str, color); 
  28. int main() 
  29.     COLOR color = RED; 
  30.     printf("The name of color %d is '%s'. \n", color, get_color_name(color)); 
  31. return 0; 

posted on 2014-07-30 15:25  Worldsing  阅读(810)  评论(0编辑  收藏  举报