Search code examples
cunsigned-integer

Use of unsigned int in different cases?


I want to ask what is the difference between these two cases ?

Case1:

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

It will result in an infinite loop!

Case2:

unsigned int a=-5;
printf("%d",a);

It will print -5 on the screen.

Now the reason for case 1 is that i is declared as unsigned int so it can not take negative values,hence will always be greater than 0.

But in case 2, if a cannot take negative values, why -5 is being printed???

What is the difference between these two cases?


Solution

  • i is declared unsigned so it can not take negative values

    That is correct. Most optimizing compilers will notice that, drop the condition from the loop, and issue a warning.

    In case 2, if a can not take negative values, why -5 is being printed?

    Because on your platform int and unsigned int have such a representation that assigning -5 to unsigned int and then passing it to printf preserves the representation of -5 in the form that lets printf produce the "correct" result.

    This is true on your platform, but other platforms may be different. That is why the standard considers this behavior undefined (i.e. printf could produce any output at all). If you print using the unsigned format specifier, you will see a large positive number.