anyone noticed this before?

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.

Create an account

Register a new account

• Forum Statistics

• Total Topics
628275
• Total Posts
2981760

• 10
• 11
• 17
• 10
• 9