【问题标题】:Macro in C language is not giving the desire output [duplicate]C语言中的宏没有给出期望的输出[重复]
【发布时间】:2021-11-06 18:48:56
【问题描述】:

无法理解为什么会产生这个输出。请详细说明。

下面的代码给了我想要的输出。喜欢

#include <stdio.h>
#define product(p,q) p*q
int main()
{
        printf("%d",product(5,3));

    return 0;
}

输出:

15

但下面代码中的相同逻辑和宏给了我如下输出。

#include <stdio.h>
#define product(p,q) p*q
int main()
{
    int x=3,y=4;
    printf("%d",product(x+2,y-1)); // x+2=5 and y-1=3

    return 0;
}

输出:

10

【问题讨论】:

标签: c macros


【解决方案1】:

您的问题是,“*”运算符的运算符优先级高于“+”。

尝试解开宏:

 product(x+2,y-1)
=x+2*y-1
=x+2y-1
=x-1+2x

您必须在每个运算符周围添加括号:

#define product(p,q) ((p)*(q))

【讨论】:

  • 非常感谢。现在我理解了这种输出背后的概念。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-20
  • 2015-05-30
  • 2013-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多