在C ++中的布尔乘法? [英] Boolean multiplication in c++?
问题描述
考虑以下几点:
inline unsigned int f1(const unsigned int i, const bool b) {return b ? i : 0;}
inline unsigned int f2(const unsigned int i, const bool b) {return b*i;}
F2
的语法更加紧凑,但这样做的标准保证了 F1
和 F2
是完全等同?
The syntax of f2
is more compact, but do the standard guarantees that f1
and f2
are strictly equivalent ?
此外,如果我想编译器优化这个前pression如果 B
和 I
是已知的在编译时,哪个版本我应该preFER?
Furthermore, if I want the compiler to optimize this expression if b
and i
are known at compile-time, which version should I prefer ?
推荐答案
恩,是的,无论是等价的。 布尔
是一个整数类型和真正
是保证转换为 1
在整数范围内,而假
是保证转换为 0
。
Well, yes, both are equivalent. bool
is an integral type and true
is guaranteed to convert to 1
in integer context, while false
is guaranteed to convert to 0
.
(反过来也是如此,即非零的整数值,保证转换为真正
在布尔上下文,而零整数值,保证转换为假
在布尔上下文中)。
(The reverse is also true, i.e. non-zero integer values are guaranteed to convert to true
in boolean context, while zero integer values are guaranteed to convert to false
in boolean context.)
由于您使用的无符号类型的工作,人们可以很容易想出其他的,可能是位黑客基于同样的事情,但完美的便携式实现像
Since you are working with unsigned types, one can easily come up with other, possibly bit-hack-based yet perfectly portable implementations of the same thing, like
i & -(unsigned) b
虽然一个体面的编译器应该能够自行选择最佳的实现您的任何版本。
although a decent compiler should be able to choose the best implementation by itself for any of your versions.
P.S。虽然我很大的惊喜,GCC 4.1.2编译所有的三个变种几乎从字面上看,即,它使用机器乘法指令基于乘法变。它很聪明,才能使用
变种,使其网点,这很可能使其成为最高效的实现。 cmovne
指令:
P.S. Although to my great surprise, GCC 4.1.2 compiled all three variants virtually literally, i.e. it used machine multiplication instruction in multiplication-based variant. It was smart enough to use cmovne
instruction on the ?:
variant to make it branchless, which quite possibly made it the most efficient implementation.
这篇关于在C ++中的布尔乘法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!