0

I just knew that there are many builtin functions of gcc, some of them seems to be useful.

For example, the builtin function __builtin_popcount() can count the number of one’s(set bits) in an integer.

Well, I know that different compiler may have different builtin function so using __builtin_popcount() may cause some portability issue. But if we ignore this issue, what is the difference between builtin function and common c/c++ code? You see we can easily make a piece of code to count the number of one's(set bits) in integer too.

int main(void)
{

    int i = 5;
    std::cout << __builtin_popcount(i) << std::endl;

    int j = 5;
    std::bitset<32> bits = j;
    std::cout << bits.count() << std::endl;

    int k = 5;
    int counter = 0;
    while (k != 0) {
        if ((k & 1) == 1) {
            counter++;
        }
        k >>= 1;
    }
    std::cout << counter << std::endl;

    return 0;
}

Let's look at this code. We can use bitset or a simple loop to count the number of bits, and also, we can use the builtin function __builtin_popcount() to do so. So what's the difference between them? If I use the builtin function, does it mean that I could get a better performance? Should I use the builtin function in my common c/c++ project?

Yves
  • 11,597
  • 17
  • 83
  • 180
  • 1
    Always prefer standard code unless you need a built-in that does something the language can't do, which you almost certainly don't. They're mostly just there to support standard library implementations. – Jason C Jan 29 '21 at 01:40
  • @JasonC Alright, I got it. – Yves Jan 29 '21 at 01:44
  • 1
    Not all hardware has the instruction to count the number of bits in an integer. So there is no Standard way of doing this. GCCs intrinsic will use the hardware instruction, if available, or resort to code (similar to the loop above) if it is not. – Richard Critten Jan 29 '21 at 01:44

0 Answers0