因为宏只是字符串替换,它发生在完成过程之前。编译器将没有机会看到宏变量及其值。例如:如果一个宏被定义为
#define BAD_SQUARE(x) x * x
并像这样称呼
BAD_SQUARE(2+1)
编译器会看到这个
2 + 1 * 2 + 1
这可能会导致意想不到的结果
5
要纠正这种行为,您应该始终用括号括住宏变量,例如
#define GOOD_SQUARE(x) (x) * (x)
例如,当调用此宏时,像这样
GOOD_SQUARE(2+1)
编译器会看到这个
(2 + 1) * (2 + 1)
这将导致
9
此外,这里有一个完整的例子来进一步说明这一点
#include <stdio.h>
#define BAD_SQUARE(x) x * x
// In macros alsways srround the variables with parenthesis
#define GOOD_SQUARE(x) (x) * (x)
int main(int argc, char const *argv[])
{
printf("BAD_SQUARE(2) = : %d \n", BAD_SQUARE(2) );
printf("GOOD_SQUARE(2) = : %d \n", GOOD_SQUARE(2) );
printf("BAD_SQUARE(2+1) = : %d ; because the macro will be \
subsituted as 2 + 1 * 2 + 1 \n", BAD_SQUARE(2+1) );
printf("GOOD_SQUARE(2+1) = : %d ; because the macro will be \
subsituted as (2 + 1) * (2 + 1) \n", GOOD_SQUARE(2+1) );
return 0;
}