3

I'm not sure how the while loop works in the following simple piece of code

short CountBits(unsigned int x){
    short num_bits = 0;
    while (x){
        num_bits += x & 1;
        x >>= 1;
    }
    return num_bits;
}

How does an unsigned integer evaluate to True or False?

Sentinel
  • 441
  • 1
  • 6
  • 25

4 Answers4

5

In the given context, x must be converted to true or false.

From the C++11 Standard (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.

Think of

while (x){ ... }

as

while (x != 0){ ... }
R Sahu
  • 204,454
  • 14
  • 159
  • 270
2

True is any integer which is not equal to 0. Thus if x evaluates to 0 then the loop breaks.

Archmede
  • 1,592
  • 2
  • 20
  • 37
2

"How does an unsigned integer evaluate to True or False"? The same way any numeric value evaluates to true or false: 0 is false, any other value is true. Some people would write the test as while (x != 0); that's exactly the same thing.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
1

For any integral number in C++, on most machines, 0 will evaluate to false. As such, when X becomes 0, the loop will terminate. The loop will continue while x is a non-zero value.

Rachel Casey
  • 205
  • 2
  • 11
  • 2
    Tell us more about those machines where the loop doesn't terminate when `x` becomes `0` – M.M May 01 '17 at 05:18
  • 1
    C++ has a standard, it specifies that x being 0 does make the loop terminate – M.M May 01 '17 at 21:11