本文共 1253 字,大约阅读时间需要 4 分钟。
本文翻译总结自《Advanced Mac OS X Programming 》第一章
1. 最核心的思想就是宏只是纯粹字面替换:
#define FIVE 5
int max = FIVE;
2. 变量要加括号:
#define SQUARE(x) x*x, 在计算SQUARE(3+5)的时候就会被替换成:3+5*3+5,正确的定义应该是#define SQUARE(x) (x)*(x)
3. 避免使用有副作用的运算,如SQUARE(i++),因为你不不知道会被展开成什么。
4. 在if中使用宏:
#define LOG_ERROR(desc)\
error_count++;\
fprintf(stderr, "Found an error '%s' at file %s, Line %d\n",\
desc, __FILE__, __LINE__)
在if代码中如果这样使用,就OK:
if(returnVal != 0){
LOG_ERROR("Here is an error!);
}
但是如果省略了大括号,将出现问题:
if(returnVal != 0) LOG_ERROR("Here is an error!);
代码将被展开为:
if(returnVal != 0)
error_count++;
fprintf(stderr, "Found an error '%s' at file %s, Line %d\n", desc, __FILE__, __LINE__)
如果需要在if中使用,就要这样定义:
#define FOUND_AN_ERROR(desc) \ do{ \
error_count++; \
fprintf(stderr, "Found an error '%s' at file %s, line %d\n", \
desc, __FILE__, __LINE__); \
} while (0)
整个宏就称为一个语句了,无论在if中如何使用也没有问题了。
5. 可变参数宏:
#define THING(string, ...) printf (string, __VA_ARGS__)
使用:
THING ("hello %s %s\n", "there", "george");
被展开成:
printf ("hello %s %s\n", "there", "george");
没有问题,但是如果没有参数,则会产生编译错误:
THING ("hello world!");
被展开成:
printf ("hello world!",);
解决这个问题的办法是使用字符串连接符号##
#define THING(string, ...) printf (string,## __VA_ARGS__)
这样就会展开成为
printf ("hello world!");
如果可变参数被忽略或为空,“##”操作将使预处理器去除掉它前面的那个逗号。
转载地址:https://blog.csdn.net/weixin_32570803/article/details/117175412 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!