从宏功能中获得错误的值

Getting a wrong value from the macro function

本文关键字:错误 宏功能      更新时间:2023-10-16

最近我正在研究宏,我陷入了非常简单的问题。这是我的代码:

#include <iostream>
#define abs(A) (A<0)? -A:A;
using namespace std;
int dis(int x, int y)
{
   return abs(x-y);
}
int main()
{
    cout<<dis(2,4);
}

基本上abs()采用给定值的绝对值,然后计算距离。但是在这种情况下,它给出输出-6而不是2。

这是因为对宏的评估方式,即在代码编译过程的预处理器阶段,return abs(x-y)将更改为:

return abs(x-y)
(A<0)          -> -A
(2-4) < 0 = -2 -> -2-4 = -6

您应该通过将宏变量包装在括号中,更改宏(更好的解决方案)的定义,以:

#define abs(A) ((A)<0) ? -(A):(A);

或将代码更改为:

int dis(int x, int y)
{
   int res = x-y;
   return abs(res);
}

请注意,C标准库中还有abs()功能。