Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of unsigned int in different cases? [duplicate]

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?

like image 702
Mrigank Avatar asked Feb 12 '23 12:02

Mrigank


2 Answers

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.

like image 184
Soren Avatar answered Feb 15 '23 12:02

Soren


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.

like image 30
haccks Avatar answered Feb 15 '23 11:02

haccks