I just programmed a simple reverse loop like this:
for (unsigned int i = 50; i >= 0; i--)
printf("i = %d\n", i);
but it doesn't stop at 0 as expected but goes down far to the negative values, why?
See this ideone sample: http://ideone.com/kkixx8
(I tested it in c# and c++)
You declared the int as unsigned. It will always be >= 0. The only reason you see negative values is that your printf call interprets it as signed (%d) instead of unsigned (%ud).
Although you did not ask for a solution, here are two common ways of fixing the problem:
// 1. The goes-to operator
for (unsigned int i = 51; i --> 0; )
printf("i = %d\n", i);
// 2. Waiting for overflow
for (unsigned int i = 50; i <= 50; i--)
printf("i = %d\n", i);
An unsigned int can never become negative.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With