unsigned integers in C

amitshree picture amitshree · Mar 11, 2013 · Viewed 46.8k times · Source

While i am running the program below it outputs like 109876543210-1-2-3-4-5-6-78-9-10-11-12-and s0 on. Why so? What is the concept of unsigned integer?

 main ()
   {
      unsigned int i;
       for (i = 10; i >= 0; i--)
                 printf ("%d", i);
   }

Answer

Vicky picture Vicky · Mar 11, 2013

Unsigned integers are always non-negative, that is greater than or equal to 0. When you subtract 1 from 0 in an unsigned integer type you end up with MAX_INT.

Therefore, your for loop will never terminate.

However, you need to use "%u" not "%d" in your printf if you want it to print the unsigned value rather than the signed value.