# signed/unsigned int

This is a discussion on signed/unsigned int within the C Programming forums, part of the General Programming Boards category; Ill get to the point why cant i do: for (unsigned int i = 4; i >= 0; i--) but ...

1. ## signed/unsigned int

Ill get to the point

why cant i do:

for (unsigned int i = 4; i >= 0; i--)

but i can do

for (int i = 4; i >= 0; i--)

if i try the first line, it counts down from 4.2 billion or something

what i dont understand is why only the second one works, an unsigned int can have a value of 4 without
overflowing and so can a signed integer, but why doesnt it work with unsigned integers?

is it a bug? or am i doing something wrong?

[EDIT] Compiler is MSVC 6

2. The for loop first works at carrying out the the mathematical operation of "i--" and then checks the condition of i>=0

When you make is unsigned and then when i =0 after that it once again performs i = i -1 so in this case i = 0-1 .
Now since you have it as unsigned it creates problems by genrating random outputs.

if you keep (unsigned int i =4;i>0;i--)
There should be no problem

3. >Now since you have it as unsigned it creates problems by genrating random outputs.
There's nothing random about it. Unsigned underflow wraps around to the largest value for the type. The problem is that the loop is infinite because an unsigned integer cannot hold a value less than 0 whereas a plain integer, which is signed, can. The behavior is well defined, so the following loop is incorrect:
Code:
`for (unsigned i = n; i >= 0; i--)`

4. Aha i didnt think of that, thanks guys