c++ - 以下函数返回什么?

标签 c++ c return output generic-programming

int fn(unsigned int x)
{
int count = 0 ;
for(; x!=0; x&=(x-1))
    count ++;
return count;
}

我在编译器中试过了,但无法弄清楚发生了什么。我认为这与 x 中的位数有关,但是什么?

最佳答案

这是一个bit trick . :)

您要返回设置为 1 的位数。

关于c++ - 以下函数返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15876841/

相关文章:

c++ - 在 C++ 中对字符串使用 #define

c++ - 链表中的节点 *next

c - 在给定函数指针的情况下反转比较函数结果

c# - “not all code path return a value”错误在方法中发生,但我确实使用了一些if语句来覆盖所有情况

javascript - 如何遍历数组并返回匹配值

C++ 程序不会在返回时结束

c++ - OpenGL矩形莫名其妙地占据了整个窗口

c++ - union 中的 Flatbuffers 结构不起作用 (C++)

c++ - 如何驯服 Windows header (有用的定义)?

c - Linux内核列表实现会导致UB吗?