我有一个简单测试的小问题:我有一个具有 3 个级别的记录器,LOG
、DEBUG
和 ERROR
。在编译时,我用我需要的值之间的按位或运算定义了级别错误。但是,当我尝试使用收到的类型消息测试 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
最佳答案
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));
不是你想要的。
总是用括号括起宏定义:
- 将展开式中的所有宏参数括起来
- 在完整的表达式两边加上括号,以防止像上面那样的优先级错误。
关于C 或#define 和 int 之间的按位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41817527/