# anyone noticed this before?

This topic is 3815 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I was recently debugging an Image loader and this was a problem:
for(unsigned u = 10; u >= 0; --u)
std::cout << u << std::endl;


it starts at (2^32) and decrements to 0 (I'm guessing), any reason why this is? I know that every (>= 0)condition is true with an unsigned l-value but would this still not be valid?

##### Share on other sites
Well, what do you expect to happen when u is zero and you decrement it? Something must happen, and generally two things does happen; wrap-around or saturation. Wrap-around means the bit pattern wraps around and starts over at "the other end", which likely means 232-1. Saturation means it stays at zero. Either way, that loop cannot exit.

##### Share on other sites
Try this:

unsigned u = 0;std::cout << u-1 << '\n';

All will become clear.

##### Share on other sites
I understand now: two's complement

0x00000000 - 0x00000001

= 0xFFFFFFFE + 0x00000001 = 0xFFFFFFFF

I should have thought about it a bit longer.

##### Share on other sites
Quote:
 Original post by staticVoid2I understand now: two's complement0x00000000 - 0x00000001= 0xFFFFFFFE + 0x00000001 = 0xFFFFFFFFI should have thought about it a bit longer.

That, and this loop will run forever because an unsigned integer will never be less than zero.

##### Share on other sites
If you're writing any loops where you're comparing against the max or min of the type, you have to change the way you write the loop. This is actually one reason I've never been completely fond of C++'s for loops. In other languages like Ada, when you write a loop like this:

for variable in reverse 10 .. 0 loop   -- do somethingend loop;

That sort of loop actually stops when it hits 0, rather than trying to test one below.

##### Share on other sites
Quote:
 Original post by Brother BobWell, what do you expect to happen when u is zero and you decrement it? Something must happen, and generally two things does happen; wrap-around or saturation. Wrap-around means the bit pattern wraps around and starts over at "the other end", which likely means 232-1. Saturation means it stays at zero. Either way, that loop cannot exit.

C++ explicitly requires an unsigned type to wrap. Just so you know.

1. 1
Rutin
47
2. 2
3. 3
4. 4
5. 5

• 13
• 10
• 12
• 10
• 13
• ### Forum Statistics

• Total Topics
632994
• Total Posts
3009769
• ### Who's Online (See full list)

There are no registered users currently online

×