使用#define函数获取错误的值 [英] Getting wrong value with #define function

查看:48
本文介绍了使用#define函数获取错误的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个用两种不同方式定义的函数,一种使用#define,另一种使用一个函数.但是对于输出,我得到了不同的值.

There is one function defined in two different ways, one using #define and other using a function. But for the output I am getting different values.

输出结果为 3 -1 .

我想知道为什么使用 F(x,y)会产生不同的值.

I want to know why using F(x,y) results in different values.

#include<iostream>
#define F(x,y) y-x
using namespace std;

int F2(int x,int y)
{
    return y-x;
}

int main()
{
    int x=1,y=2, h=2;
    cout << F(x+h,y) << " " << F2(x+h,y) << endl;
    return 0;
}

推荐答案

使用 #define 的经典问题,也是不鼓励使用宏的主要原因之一.请记住,宏只不过是文字上的替换,请考虑将其扩展为:

Classic problem using #define, and one of the main reasons why macros are discouraged. Keep in mind that a macro is little more than a literal substitution, and consider what it expands to:

cout << y-x+h << " " << F2(x+h,y) << endl;

y-x + h y-(x + h)非常不同.

总是用括号括住宏参数的使用:

Always parenthesize uses of macro arguments:

#define F(x,y) ((y)-(x))

这篇关于使用#define函数获取错误的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆