search

Home  >  Q&A  >  body text

c++宏定义问题

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

#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只被递增一次!!

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

高洛峰高洛峰2803 days ago604

reply all(6)I'll reply

  • 黄舟

    黄舟2017-04-17 13:06:46

    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.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 13:06:46

    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; }) 

    reply
    0
  • 阿神

    阿神2017-04-17 13:06:46

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

    reply
    0
  • 迷茫

    迷茫2017-04-17 13:06:46

    @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.

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 13:06:46

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

    reply
    0
  • 黄舟

    黄舟2017-04-17 13:06:46

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

    reply
    0
  • Cancelreply