问题
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