简体   繁体   English

C #define宏

[英]C #define macros

Here is what i have and I wonder how this works and what it actually does. 这就是我所拥有的,我想知道它是如何工作的以及它实际上做了什么。

#define NUM 5
#define FTIMES(x)(x*5)

int main(void) {
    int j = 1;
    printf("%d %d\n", FTIMES(j+5), FTIMES((j+5)));
}

It produces two integers: 26 and 30. 它产生两个整数:26和30。

How does it do that? 它是如何做到的?

The reason this happens is because your macro expands the print to: 发生这种情况的原因是因为您的宏将打印扩展为:

printf("%d %d\n", j+5*5, (j+5)*5);

Meaning: 含义:

1+5*5 and (1+5)*5

Since it hasn't been mentioned yet, the way to fix this problem is to do the following: 由于尚未提及,解决此问题的方法是执行以下操作:

#define FTIMES(x) ((x)*5)

The parentheses around x in the macro expansion prevent the operator associativity problem. 宏扩展中围绕x的括号可防止运算符关联性问题。

define is just a string substitution. define只是一个字符串替换。

The answer to your question after that is order of operations: 之后您的问题的答案是操作顺序:

FTIMES(j+5) = 1+5*5 = 26 FTIMES(j + 5)= 1 + 5 * 5 = 26

FTIMES((j+5)) = (1+5)*5 = 30 FTIMES((j + 5))=(1 + 5)* 5 = 30

The compiler pre-process simply does a substitution of FTIMES wherever it sees it, and then compiles the code. 编译器预处理只是在FTIMES看到它的地方进行替换,然后编译代码。 So in reality, the code that the compiler sees is this: 所以实际上,编译器看到的代码是这样的:

#define NUM 5
#define FTIMES(x)(x*5)

int main(void)
{

    int j = 1;

    printf("%d %d\n", j+5*5,(j+5)*5);
}

Then, taking operator preference into account, you can see why you get 26 and 30. 然后,考虑到操作员偏好,你可以看到为什么你得到26和30。

如果你想修复它:

#define FTIMES(x) ((x) * 5)

the preprocessor substitutes all NUM ocurrences in the code with 5, and all the FTIMES(x) with x * 5. The compiler then compiles the code. 预处理器用5替换代码中的所有NUM个事件,用x * 5替换所有FTIMES(x)。然后编译器编译代码。

Its just text substitution. 它只是文字替换。

Order of operations. 运作顺序。

FTIMES(j+5) where j=1 evaluates to: 其中j = 1的FTIMES(j + 5)评估为:

1+5*5 1 + 5 * 5

Which is: 这是:

25+1 25 + 1

=26 = 26

By making FTIMES((j+5)) you've changed it to: 通过制作FTIMES((j + 5)),您已将其更改为:

(1+5)*5 (1 + 5)* 5

6*5 6 * 5

30 三十

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

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