Search code examples
c++c++20bit

Why do operation on <bit> return signed numbers?


Operations like

template< class T >
constexpr int popcount( T x ) noexcept;

return a signed integer, but the number of set bits can never be negative? What was the motivation for choosing a signed rather than unsigned type?


Solution

  • From the paper:

    The counting operations return "int" quantities, consistent with the rule "use an int unless you need something else". This choice does not reflect, in the type, the fact that counts are always non-negative.

    gcc's intrinsic here (__builtin_popcount) also returns int.