Boolean multiplication in c++?

10,367

Solution 1

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. 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.

Solution 2

Yes. It's safe to assume true is 1 and false is 0 when used in expressions as you do and is guaranteed:

C++11, Integral Promotions, 4.5:

An rvalue of type bool can be converted to an rvalue of type int, with false becoming zero and true becoming one.

Solution 3

The compiler will use implicit conversion to make an unsigned int from b, 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.

Share:
10,367
Vincent
Author by

Vincent

Researcher, astrophysicist, computer scientist, programming language expert, software architect and C++ standardization committee member. LinkedIn: https://www.linkedin.com/in/vincent-reverdy

Updated on June 02, 2022

Comments

  • Vincent
    Vincent almost 2 years

    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 ?