A min= idiom in C++?

后端 未结 7 934
旧巷少年郎
旧巷少年郎 2021-02-09 22:10

We use

x += y

instead of

x = x + y

And similarly for *,/,- and other operators. Well, what about

7条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-09 23:00

    No, it is not possible to create new custom operators.

    You have a few available solutions though:

    llama_min_age = std::min(x, y);
    llama_min_age = (x < y ? x : y);
    

    Or even a macro if you want to:

    #define MIN(x, y) ((x) < (y) ? (x) : (y))
    

    About the macro: it can lead to vicious bug, so I would prefer to use one of the first two solutions.

提交回复
热议问题