Sign in to follow this  

anyone noticed this before?

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

If you intended to correct an error in the post then please contact us.

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
Try this:


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


All will become clear.

Share this post


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