输出结果令人困惑

标签 c macros

我只是好奇为什么输出是 4 而不是 6 。你们中有人可以帮忙解释一下他们的过程吗?

#include <stdio.h>
#define AMT1 a+a+a
#define AMT2 AMT1 - AMT1
main()
{
int a=1;
printf (“Amount is %d\n”,AMT2);
}

谢谢

最佳答案

AMT2 = AMT1 - AMT1
AMT2 = a+a+a - a+a+a
AMT2 = 1+1+1 - 1+1+1
AMT2 = 3 -     1 + 1 + 1
AMT2 = 2         + 1 + 1
AMT2 = 3             + 1
AMT2 = 4

宏的第一条规则是:所有内容都需要用括号括起来。你想要:

#define AMT2 (AMT1) - (AMT1)

关于输出结果令人困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64798687/

相关文章:

c - 打印带重复的排序排列

macros - 让表格: How to access destructured symbols in a macro?

macros - 如何将引用的 sexp 传递给宏

我可以附加到预处理器宏吗?

c++ - 无法调用 std::max 因为 minwindef.h 定义了 "max"

c - _v(l) 在宏中的意义是什么?

c - C 中的 "Dynamic Inheritance"

c - 在 ncurses 上重绘

从 C++/CLI Visual studio 2010 调用使用 VS 2005 编译的 native C - 无法打开 .lib 文件...

c++ - 为什么编译器不能优化0浮点加法?