While loop with unsigned integer condition

I am 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?

+3


source to share


4 answers


In this context, x

it must be converted to true

or false

.

From the C ++ 11 standard (4.12 / 1):

An arithmetic, unenumerated enumeration, pointer, or pointer to member type value can be converted to a prvalue of type bool

. A null value, a null pointer value, or a null element pointer value is converted to false

; any other value is converted to true

.

Think about



while (x){ ... }

      

and

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

      

+5


source


True is any integer that is not 0. Thus, if x evaluates to 0, then the loop is aborted.



+2


source


"How does an unsigned integer evaluate to True or False? Likewise, any numeric value evaluates to true

either false

: 0 is false

, any other value true

. Some people write the test as while (x != 0)

; it is the same."

+2


source


For any integer number in C ++ on most machines, 0 will evaluate to false. Thus, when X becomes 0, the loop ends. The loop will continue and x is a nonzero value.

+1


source







All Articles