在c程序中使用宏

时间:2017-03-10 18:55:43

标签: c macros

我用宏来搞定这个愚蠢的程序,但我不知道失败是什么:

#include <stdio.h>
#include <stdlib.h>

#define READ_RX  (1 << 1)
#define WRITE_RX (1 << 2)
#define READ_TX  (1 << 3)
#define WRITE_TX (1 << 4)

#define READ_COMMAND(num) (num == 0) ? (READ_RX) : (READ_TX)
#define WRITE_COMMAND(num) (num == 0) ? (WRITE_RX) : (WRITE_TX)

int main(int argc, char **argv)
{

    printf("[DEBUG] 0x%04X\n", (READ_COMMAND(0)) | (WRITE_COMMAND(0))); //works fine
    printf("[DEBUG] 0x%04X\n", READ_COMMAND(0) | WRITE_COMMAND(0)); //doesn't work

    return 0;
}

结果:

$ ./test
[DEBUG] 0x0006 -> works fine
[DEBUG] 0x0002 -> doesn't work

有谁知道这是什么问题?

最好的问候。

2 个答案:

答案 0 :(得分:5)

宏只是文本替换,意思是什么。 即。

(READ_COMMAND(0)) | (WRITE_COMMAND(0))

变为

((num == 0) ? (READ_RX) : (READ_TX)) | ((num == 0) ? (READ_RX) : (READ_TX))

READ_COMMAND(0) | WRITE_COMMAND(0)

成为

(num == 0) ? (READ_RX) : (READ_TX) | (num == 0) ? (READ_RX) : (READ_TX)

现在使用优先规则,您可以看到,这与

相同
(num == 0) ? (READ_RX) : ( (READ_TX) | (num == 0) ? (READ_RX) : (READ_TX) )

答案 1 :(得分:3)

你需要围绕整个定义的大括号。第二个扩展到:

(num == 0) ? (2) : (8) | (num == 0) ? (1) : (4)

请注意|的优先级高于? :运算符的优先级。