c语言的宏因为本质是字符替换,不是类型安全的行为,但也因为其字符替换的本质使其具有了一些编译期的动态特性,对于一些特殊的场合就非常的有用,比如下面的打日志。
宏的使用这篇文章写的很不错,C语言宏的特殊用法和几个坑.
#include <stdio.h>
typedef enum
{
ERROR_ONE, // 0
ERROR_TWO,
ERROR_THREE,
ERROR_END
}E_ERROR_CODE;
unsigned long g_error_statistics[ERROR_END] = {0};
/* LOG 打印, # 直接常亮字符串替换 */
#define LOG_PRINT(ERROR_CODE) \
do { \
g_error_statistics[ERROR_CODE]++; \
printf("[%s : %d], error is %s\n", __FILE__, __LINE__, #ERROR_CODE); \
} while (0)
/* ERROR 公共前缀,传参时省略的写法, ## 直接展开拼接 */
#define LOG_PRINT_2(CODE) \
do { \
g_error_statistics[ERROR_ ## CODE]++; \
printf("[%s : %d], error is %s\n", __FILE__, __LINE__, "ERROR_" #CODE); \
} while (0)
int main()
{
LOG_PRINT(ERROR_TWO);
LOG_PRINT_2(ONE);
for (unsigned int i = 0; i < ERROR_END; ++i) {
printf("error %u statistics is %lu \n", i, g_error_statistics[i]);
}
return 0;
}