gpt4 book ai didi

c++ - 当 define 对运算符有值(value)时,#define 如何在编程中工作?

转载 作者:太空宇宙 更新时间:2023-11-04 05:11:59 24 4
gpt4 key购买 nike

我在理解#define 的工作原理时遇到了问题。

#include<stdio.h>
#define x 6+3
int main(){

int i;
i=x; //9
printf("%d\n",i);
i=x*x; //27
printf("%d\n",i);
i=x*x*x; //45
printf("%d\n",i);
i=x*x*x*x; //63
printf("%d\n",i);

return 0;
}

如果我使用 #define x 6+3 输出是 9 27 45 63

如果我使用 #define x (6+3) 输出是 9 81 729 6561

最佳答案

#define 只是将字符标记(在您的情况下为 x)替换为您定义的内容。因此,在预处理器完成工作后,您的示例将如下所示:

#include<stdio.h>
#define x 6+3
int main(){

int i;
i=6+3; //9
printf("%d\n",i);
i=6+3*6+3; //27
printf("%d\n",i);
i=6+3*6+3*6+3; //45
printf("%d\n",i);
i=6+3*6+3*6+3*6+3; //63
printf("%d\n",i);

return 0;

}

如果您查看它,您就会明白为什么,例如第二个例子是 27 而不是 81(* 在 + 之前)。

另一方面,如果您编写 (6+3),它将是 9*9,这就是您所期望的。

关于c++ - 当 define 对运算符有值(value)时,#define 如何在编程中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46843598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com