我不确定while循环如何在以下简单的代码中工作
short CountBits(unsigned int x){
short num_bits = 0;
while (x){
num_bits += x & 1;
x >>= 1;
}
return num_bits;
}
Run Code Online (Sandbox Code Playgroud)
无符号整数如何计算为True或False?
在给定的上下文中,x必须转换为true或false.
从C++ 11标准(4.12/1):
算术,无范围枚举,指针或指向成员类型的指针的prvalue可以转换为类型的prvalue
bool.将零值,空指针值或空成员指针值转换为false; 任何其他值都转换为true.
考虑到
while (x){ ... }
Run Code Online (Sandbox Code Playgroud)
如
while (x != 0){ ... }
Run Code Online (Sandbox Code Playgroud)