Ask your own question, for FREE!
Computer Science 7 Online
OpenStudy (anonymous):

C: unsigned int counting down to 0. How? This implementation is broken :P I know why. I fixed it later by removing the condition for i and increment for i and put it at the end of the body (break if i == 0) I'm wondering if there is a way with the entire for statement to do this loop though (ie reach 0). http://ideone.com/Qm5V0

OpenStudy (shadowfiend):

The last iteration where i is 0 still returns i >= 0. You then subtract 1 from i. If i were signed (meaning it could go negative), you would end up with i = -1, which is not >= 0. However, i is unsigned (note that you're using %d to printf it, so printf interprets it as a *signed* integer, thus it is displaying negatives). Because i is unsigned, subtracting 1 makes it wrap to UINT_MAX. To see what C actually sees, use %u in printf to print it as an unsigned integer -> http://ideone.com/l58zE Therefore, i is always >= 0, thus why the loop never terminates.

OpenStudy (shadowfiend):

x_x Definitely should have read more. To reach 0, I would say i + 1 <= 1.

OpenStudy (anonymous):

haha, integer underflow :-P For something like this, you might want to use the "goes down to" operator: --> http://ideone.com/Efgz2

OpenStudy (anonymous):

if you want it to fit in the entire loop, just initialize i to 11: http://ideone.com/Wdi78

OpenStudy (anonymous):

It's not a for loop but that goes down to operator had me for a second lol. Good answer.

OpenStudy (anonymous):

if you need a for loop, then you can do this: http://ideone.com/cFJip

OpenStudy (anonymous):

Impressive!

OpenStudy (anonymous):

actually, my solution still has the integer underflow problem. if you print the value of i right after the loop...

OpenStudy (anonymous):

at least if you do it like this: http://ideone.com/adFrC then there will be no integer underflow problem with i

OpenStudy (anonymous):

or if you do what shadowfiend suggested: http://ideone.com/iuYCK although after the loop, the value of i is UINT32_MAX

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!