<分区>
我不确定 while 循环在下面这段简单的代码中是如何工作的
short CountBits(unsigned int x){
short num_bits = 0;
while (x){
num_bits += x & 1;
x >>= 1;
}
return num_bits;
}
无符号整数如何计算为 True 或 False?
标签 c++
<分区>
我不确定 while 循环在下面这段简单的代码中是如何工作的
short CountBits(unsigned int x){
short num_bits = 0;
while (x){
num_bits += x & 1;
x >>= 1;
}
return num_bits;
}
无符号整数如何计算为 True 或 False?
最佳答案
在给定的上下文中,x
必须转换为 true
或 false
。
来自 C++11 标准 (4.12/1):
A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type
bool
. A zero value, null pointer value, or null member pointer value is converted tofalse
; any other value is converted totrue
.
想想
while (x){ ... }
作为
while (x != 0){ ... }
关于c++ - while 无符号整数条件循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43713204/