Modifiers int, unsigned and signed in C language

1

Algorithm "handle age":

// idade deve sempre ser positiva, por isso vou usar unsigned
unsigned int t1;
printf("Digite sua idade:");
scanf("%d", &t1);
printf("Idade: %d", t1);

Doubt: Even though I enter with a negative value, 2 printf() appears negative. I did not understand the actual use of the modifier unsigned of int ?

    
asked by anonymous 21.10.2017 / 02:39

2 answers

2

When you use the %d modifier you are indicating a value of the signed integer type, in this case negative. The correct switch for unsigned is %u . Internally, both signal and non-signal ends using the same number of bits. The difference is that in the case with sign, it uses the most significant bit to indicate the signal used.

    
21.10.2017 / 02:47
3

If you want to accept only positives you have to filter properly ( if (t1 >= 0) ).

The type unsigned int indicates only that it will be an unsigned number, it does not prohibit entering a negative number. It is possible to store an originally negative number in it where it loses the signal and generates a very different positive number than you expect.

    
21.10.2017 / 02:51