c++宏定义问题
高洛峰
高洛峰 2017-04-17 13:04:46
0
6
575

我以前写过这样的宏替换代码:

#define MAX(a, b) ((a) > (b) ? (a):(b)) //得到两个数中的最大值

在每个变量外都加了括号以后,使用起来确实没碰到过什么问题。可是作者这样使用 这个函数:

int a = 5, b = 0;
MAX(++a, b); //a会被递增两次
MAX(++a, b+10); //由于b+10>a,a只被递增一次!!

问:问题产生原因?解决方案?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(6)
黄舟

First of all, you have to understand that define is a simple replacement. This is the first point. Based on this, we will use macros to replace the two expressions you provided, and then you will understand.

((a) > (b) ? (a) : (b)) =>  ((++a) > (b) ? (++a) : (b))
((a) > (b) ? (a) : (b)) =>  ((++a) > (b+10) ? (++a) : (b+10))

You should fill in the values ​​and calculate them, and you should understand.

First determine whether a is greater than b, then a ++ operation will be performed; when a is greater than b, the ++a expression will be returned, and a ++ operation will be performed again; what I said is a bit convoluted, I think You should know what I mean.

The solution is not to use operators in macros that will change their own values, such as ++, --, etc. This will make you dizzy.

Peter_Zhu

http://www.cnblogs.com/safeking/archive/2008/03/21/1116302.html

The minimal way to define macros without side effects (linux kernel definition)

159: #define min_t(type,x,y) \
160:         ({ type __x = (x); type __y = (y); __x < __y ? __x: __y; }) 
阿神

Write them separately. Obviously, the side effects were not considered when defining the macro

迷茫

@brayden’s method is useless because it is not standard C/C++ syntax

I don’t know why you have to use macros, because you said you are using C++, and obviously you should use template functions to solve this problem:

template<typename T>
T Max(T a, T b)
{
    return a > b ? a : b;
}

Of course, C++ has already considered this problem, so you have std::max to use.

巴扎黑

You have to learn basic grammar. The execution logic of conditional expressions needs to be clarified

黄舟

The template is great, classmate, this is Effective c++ code hahaha, I am also reading it, we can discuss with each other

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!