Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Is Comparing if an Unsigned Int >= 0 a "Pointless Comparison"?

Tags:

I got warning:

Pe186 "Pointless comparison of unsigned int with zero"

when I tried to compile the following code:

for(clLoop = cpLoopStart; clLoop >= 0; clLoop--)                                   {     //Do something } 

I don't understand why. I could understand, if I were looking for a value less than zero, since an unsigned int can never be negative. But all I am looking for here is if it is equal to zero, which an unsigned int certainly can be.

I could even see this error if in this loop I tried to pre-decrement instead of post-decrement, but again that is not the case.

like image 539
Josh Avatar asked Feb 21 '11 13:02

Josh


People also ask

What is special about an unsigned integer?

Unsigned Integers (often called "uints") are just like integers (whole numbers) but have the property that they don't have a + or - sign associated with them. Thus they are always non-negative (zero or positive). We use uint's when we know the value we are counting will always be non-negative.

Can int and unsigned compare?

Yes, it does matter. On a platform with 32bit int with e.g. int x = -1; unsigned y = 0xffffffff; the expression x == y would yield 1 because through the "usual arithmetic conversions" the value of x is converted to unsigned and thus to 0xffffffff .

Is unsigned int better to use?

The Google C++ style guide recommends avoiding unsigned integers except in situations that definitely require it (for example: file formats often store sizes in uint32_t or uint64_t -- no point in wasting a signedness bit that will never be used).

Can you be unsigned zero?

An unsigned variable type of int can hold zero and positive numbers, and a signed int holds negative, zero and positive numbers. In 32-bit integers, an unsigned integer has a range of 0 to 232-1 = 0 to 4,294,967,295 or about 4 billion.


1 Answers

You check whether the unsigned int is greater than or equal (>=) zero. This expression will always be true, because unsigned integers will never be less than zero.

The compiler tries to warn you that you are about to program an infinite loop.

like image 149
Timbo Avatar answered Sep 20 '22 02:09

Timbo