Using unsigned int in different cases?

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

Option 1:

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

This will lead to an endless loop!

Case 2:

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

It will display -5 on the screen.

Now the reason for case 1 is that it is ideclared as unsigned int, therefore it cannot take negative values , therefore it will always be greater than 0.

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

What is the difference between these two cases?

+4
source share
3 answers

i is declared unsigned, so it cannot take negative values

. , .

2, a , -5 ?

int unsigned int , -5 to unsigned int, printf -5 , printf "" .

, . undefined (.. printf ). , .

+2

ave unsigned, , UINT_MAX , , .
, undefined.
. C11: 7.21.6 p (6):

, undefined. 282)

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

UINT_MAX - 5.

+3

, a .

printf("%d",a);

therefore, when a can be unsigned, then it %dasks for the printing of the binary value as the sign value. If you want to print it as unsigned value, use

printf("%u",a);

Most compilers will warn you about incompatible use of options for printf - so you'll probably understand this by looking at all the warnings and fixing them.

+3
source

Source: https://habr.com/ru/post/1548068/


All Articles