Consider the following:
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;}
The syntax of f2
is more compact, but do the standard guarantees that f1
and f2
are strictly equivalent ?
Furthermore, if I want the compiler to optimize this expression if b
and i
are known at compile-time, which version should I prefer ?
The compiler will use implicit conversion to make an
unsigned int
fromb
, so, yes, this should work. You're skipping the condition checking by simple multiplication. Which one is more effective/faster? Don't know. A good compiler would most likely optimize both versions I'd assume.Yes. It's safe to assume
true
is1
andfalse
is0
when used in expressions as you do and is guaranteed:C++11, Integral Promotions, 4.5:
Well, yes, both are equivalent.
bool
is an integral type andtrue
is guaranteed to convert to1
in integer context, whilefalse
is guaranteed to convert to0
.(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 tofalse
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
although a decent compiler should be able to choose the best implementation by itself for any of your versions.
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.FWIW, the following code
compiled with gcc -O2 produces this assembly:
There's not much left of either
f1
orf2
, as you can see.As far as C++ standard is concerned, the compiler is allowed to do anything with regards to optimization, as long as it doesn't change the observable behaviour (the as if rule).