What is the best implementation of min? [closed]

你。 提交于 2019-12-11 17:21:12

问题


Is there a difference between

int min(int a, int b) {
    return (a < b) ? a : b;
}

and

int min(int a, int b) {
    return (b < a) ? b : a;
}

Is there any specific reason to prefer one over the other?

This question is specifically intended for both the C and the C++ languages. I understand these are different languages and a similar question was asked for C++ here: Correct implementation of min .

I am interested in reasons that may pertain to one language and not the other.


回答1:


No, there isn't. The two implementations are equivalent under all defined circumstances. (An individual compiler might exhibit performance differences, but not functional differences.)

It would be different if the function weren't concerned solely with ints. Floating point numbers, as chux mentioned in a comment, can have both a<b and b<a false even when their bit patterns differ, as with negative/positive zero, or when at least one is a NaN. Technically this could also occur with an exotic (but standards-compliant) integer representation (through -0 or padding bits), but AFAIK no otherwise standards-compliant compiler does that.



来源:https://stackoverflow.com/questions/55552778/what-is-the-best-implementation-of-min

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!