C或在#define和int之间按位

时间:2017-01-23 23:27:44

标签: c

我在一个简单的测试中遇到了一些问题:我有一个包含3个级别的记录器,LOGDEBUGERROR。在编译时,我通过按位或在我需要的值之间操作来定义级别错误。但是当我尝试使用我收到的类型消息测试LEVEL时,这是错误的。如果级别为常量,5 & 2会向我1,但如果我将LEVEL放在int变量中,我就不会遇到此问题。有人知道为什么吗?

以下是 logger.h

中的定义
#define LOG 1
#define DEBUG 2
#define ERROR 4
#define LEVEL LOG | ERROR

这是 logger.c

printf("level %d\n", LEVEL);
printf("type %d\n", type);
int level = LEVEL;
printf("and %d\n", LEVEL & type);
printf("and %d\n", level & type);
printf("and %d\n", 5 & 2);

结果

level 5
type 2
and 1
and 0
and 0

1 个答案:

答案 0 :(得分:2)

LEVEL的宏定义未正确括号。请改用:

#define LEVEL  (LOG | ERROR)

使用伪造的定义,以下是printf语句扩展的方式:

printf("and %d\n", LEVEL & type);

变为:

printf("and %d\n", LOG | ERROR & type);

解析为:

printf("and %d\n", LOG | (ERROR & type));

不是你想要的。

始终将宏定义括起来:

  • 在扩展
  • 中的所有宏参数周围加上括号
  • 在完整表达式周围加上括号,以防止出现上述错误之类的优先级错误。