从宏功能中获得错误的值
Getting a wrong value from the macro function
最近我正在研究宏,我陷入了非常简单的问题。这是我的代码:
#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()
功能。
相关文章:
- MSVC多行宏编译器错误
- 对C宏的未定义引用,但在定义它时会出现重新定义错误
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 在气泡排序程序中未声明错误功能
- 错误:(-210:不支持的格式或格式组合)功能'create'中的硬件视频解码器不支持视频源
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- C++中"覆盖功能的异常规范比基本版本更宽松"的奇怪错误
- 错误:在尝试检测 std::cout 是否<< t 时,功能强制转换为数组类型;有效
- 如何在现代C++中实现没有宏的系统特定功能
- 访问我以前可以访问的功能时出现分段错误
- 用于二分搜索的错误简单功能(C++)
- 未评估上下文中的默认模板参数和 lambda:错误还是功能?
- C 继承问题错误C2084功能已经具有主体
- 为什么C 编译器选择错误的功能(模板)
- C 作为参数错误的功能
- 从宏功能中获得错误的值
- 错误调用功能无法转换类型
- 在自由函数中定义的类型,可通过自动外部访问.语言错误或功能
- 无法构建 Boost 1.59 错误:功能 "deduced-address-model" : "32" "64" : "propagated" "optional" "composite" "hid
- 程序进入错误的功能