Sign in to follow this  
staticVoid2

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 this post


Link to post
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 this post


Link to post
Share on other sites
Quote:
Original post by staticVoid2
I understand now: two's complement

0x00000000 - 0x00000001

= 0xFFFFFFFE + 0x00000001 = 0xFFFFFFFF

I 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 this post


Link to post
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 something
end loop;




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

Share this post


Link to post
Share on other sites
Quote:
Original post by Brother Bob
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.


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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this