错误例子:
#define ABS(x) (((x) < 0) ? -(x) : (x))
void func(int n) {
/* Validate that n is within the desired range */
int m = ABS(++n);
/* ... */
}
这段代码的问题在于宏扩展后n会做两次运算:m = (((++n) < 0) ? -(++n) : (++n));
正确例子:
#define ABS(x) (((x) < 0) ? -(x) : (x)) /* UNSAFE */
void func(int n) {
/* Validate that n is within the desired range */
++n;
int m = ABS(n);
/* ... */
}
或者直接写出inline 函数的形式:
#include <complex.h>
#include <math.h>
static inline int iabs(int x) {
return (((x) < 0) ? -(x) : (x));
}
void func(int n) {
/* Validate that n is within the desired range */
int m = iabs(++n);
/* ... */
}
GCC的扩展C中支持__typeof可以将宏的参数赋予一个临时变量,使宏有了类似函数的特性,不会将参数运算多次进行,而只在初使化tmp时进行:
#define ABS(x) __extension__ ({ __typeof (x) tmp = x; \
tmp < 0 ? -tmp : tmp; })
注意:assert() 宏使用时也不能有这种side effect的代码入参
宏中不能加入预处理指令如#ifdef #define,同样的也不能在系统函数中入参这样的预处理指令,因为你不知道系统函数是否是用宏实现的。
错误例子:
#include <string.h>
void func(const char *src) {
/* Validate the source string; calculate size */
char *dest;
/* malloc() destination string */
memcpy(dest, src,
#ifdef PLATFORM1
12
#else
24
#endif
);
/* ... */
}
正确的应该是:
#include <string.h>
void func(const char *src) {
/* Validate the source string; calculate size */
char *dest;
/* malloc() destination string */
#ifdef PLATFORM1
memcpy(dest, src, 12);
#else
memcpy(dest, src, 24);
#endif
/* ... */
}
本文讨论了在C/C++编程中,为何不应该在宏定义中使用带有副作用的参数表达式,以防止多次计算参数。错误的例子显示了宏可能导致的意外行为,而正确的做法是使用inline函数或GCC的__typeof__扩展来避免此类问题。同时强调,assert()宏和系统函数的参数也不应包含有副作用的代码。

397

被折叠的 条评论
为什么被折叠?



