4

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?

Erik
  • 2,137
  • 3
  • 25
  • 42
Mrigank
  • 522
  • 4
  • 13

3 Answers3

3

When a -ve value is assigned to an unsigned variable, it can't hold that value and that value is added to UINT_MAX and finally you get a positive value.
Note that using wrong specifier to print a data type invokes undefined behavior.
See C11: 7.21.6 p(6):

If a conversion specification is invalid, the behavior is undefined.282)

unsigned int a=-5;
printf("%u",a);  // use %u to print unsigned

will print the value of UINT_MAX - 5.

haccks
  • 104,019
  • 25
  • 176
  • 264
3

The difference is that you are printing a as a signed integer.

printf("%d",a);

so while a may be unsigned, then the %d is asking to print the binary value as a signed value. If you want to print it as a unsigned value, then use

printf("%u",a);

Most compilers will warn you about incompatible use of of parameters to printf -- so you could probably catch this by looking at all the warnings and fix it.

Soren
  • 14,402
  • 4
  • 41
  • 67
2

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523