min的最佳实现是什么? [英] What is the best implementation of min?

查看:149
本文介绍了min的最佳实现是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两者之间是否有区别

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

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

有什么特定的理由比另一个更偏爱吗?

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

这个问题专门针对C语言和C ++语言.我了解这些语言是不同的,并且在此处针对C ++提出了类似的问题:正确实施min

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.

推荐答案

不,没有.在所有定义的情况下,这两种实现都是等效的. (单个编译器可能会表现出性能差异,但不会表现出功能差异.)

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

如果函数不仅仅与int有关,那会有所不同.注释中提到的chux浮点数即使a<bb<a都为假,即使它们的位模式不同(例如,负数/正数为零)或至少一个为NaN时也是如此.从技术上讲,这也可能会使用奇异(但符合标准)的整数表示形式(通过-0或填充位)发生,但是AFAIK没有其他符合标准的编译器会这样做.

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.

这篇关于min的最佳实现是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆