c++ - while 无符号整数条件循环

标签 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 必须转换为 truefalse

来自 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 to false; any other value is converted to true.

想想

while (x){ ... }

作为

while (x != 0){ ... }

关于c++ - while 无符号整数条件循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43713204/

相关文章:

c++ - 这是将字符串作为参数传递给函数的内存有效方法。?

c++ - 自 C++17 的类模板参数推导以来,std::make_move_iterator 是否多余?

c++ - 使用模板输入双关语

c++ - 如何在 C++ 中使用模板制作通用 map

c++ - 如何从函数返回单个字符

c++ - 我的 wxWidgets 基于框架的应用程序需要一个顶级的 sizer 吗?

c++ - 设计模式 : inheritance and encapsulated inheritance

c# - C++ (Intel) vs Java (Hotspot) vs C# 基准问题(包括代码和结果)

C++ Armadillo 和 OpenMp : Parallelization of summation of outer products - define reduction for Armadillo matrix

c++ - 读取文件并删除重复的字母