简体   繁体   English

在c程序中使用宏

[英]Using macros in c program

I've got this silly program with macros, but I don't know what is the failure: 我用宏来搞定这个愚蠢的程序,但我不知道失败是什么:

#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;
}

Result: 结果:

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

Does anyone know what is the problem? 有谁知道这是什么问题?

Best regards. 最好的祝福。

Macros just textually replace, what they mean. 宏只是文本替换,意思是什么。 ie

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

becomes

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

whereas

READ_COMMAND(0) | WRITE_COMMAND(0)

becomes

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

Now using the precedence rules, you can see, that this is the same as 现在使用优先级规则,您可以看到,这是相同的

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

You need braces around your whole define. 你需要围绕整个定义的大括号。 The second expands to: 第二个扩展到:

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

notice that the precedence of the | 注意|的优先级 is higher than that of the ? : 是高于? : ? : operator. ? :运营商。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM