宏的问题 [英] Problem with Macros

查看:119
本文介绍了宏的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HI,

有人可以帮助我理解为什么SQUARE(x)的值是49?

Can some one help me in understanding why the value of SQUARE(x) is 49 ?

我使用Visual C ++ 6.0。

I am using Visual C++ 6.0 .

#define SQUARE(X) X * X

int main(int argc, char* argv[])
{
    int y = 5;

    printf("%d\n",SQUARE(++y));
    return 0;
}


推荐答案

Neil Butterworth,Mark和Pavel

Neil Butterworth, Mark and Pavel are right.

SQUARE(++ y)扩展为++ y * ++ y,它的值增加两倍。

SQUARE(++y) expands to ++y * ++y, which increments twice the value of y.

您可能遇到的另一个问题:SQUARE(a + b)扩展为不是(a + b)*(a + b)而是a +(b * a)的+ b * + b。在定义宏时,您需要考虑在元素周围添加括号:#define SQUARE(X)((X)*(X))的风险要小一些。 (Ian Kemp在他的评论中首先写道)

Another problem you could encounter: SQUARE(a + b) expands to a + b * a + b which is not (a+b)*(a+b) but a + (b * a) + b. You should take care of adding parentheses around elements when needed while defining macros: #define SQUARE(X) ((X) * (X)) is a bit less risky. (Ian Kemp wrote it first in his comment)

您可以使用内联模板函数(在运行时效率不低),如下所示:

You could instead use an inline template function (no less efficient at runtime) like this one:

template <class T>
inline T square(T value)
{
    return value*value;
}

您可以检查它是否正常:

You can check it works:

int i = 2;
std::cout << square(++i) << " should be 9" << std::endl;
std::cout << square(++i) << " should be 16" << std::endl;

(无需写入

square<int>(++i)

是隐含的i)

这篇关于宏的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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