Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strange behavior of reverse loop in c# and c++

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++)

like image 575
bricklore Avatar asked Apr 17 '14 07:04

bricklore


3 Answers

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).

like image 102
DrC Avatar answered Nov 16 '22 07:11

DrC


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);
like image 3
fredoverflow Avatar answered Nov 16 '22 09:11

fredoverflow


An unsigned int can never become negative.

like image 2
Alan Stokes Avatar answered Nov 16 '22 08:11

Alan Stokes