Int, unsigned and Signed modifiers in C language

Asked

Viewed 287 times

1

Algorithm "takes 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 if I enter with a negative value, 2 printf() is negative. I did not understand the actual use of the modifier unsigned of int?

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote for any question).

2 answers

3

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

The guy unsigned int indicates only that it will be a number without signal, does not prohibit entering a negative number. It is possible to store a originally negative number in it where it loses the signal and generates a very different positive number than it expects. See this at How -1 can be greater than 4?.

2


When the modifier is used %d you are indicating an integer type value with sign, in this case negative. The correct modifier for no signal is %u. Internally, both signal and signal-free end up using the same number of bits. The difference is that in the case with signal, it uses the most significant bit to indicate the signal used.

  • Not necessarily a bit is used for the signal. C standard does not require a specific form of signal storage. The most common is not even this type, but the complement of 1s. Some details in English here

  • 2

    Complement 2 is the most used. Complement 1 is only the denied bits. Often the eighth bit is called a signal bit by force of habit, because being turned on indicates that the number is negative, but not necessarily speaking this way indicates that one is using signal magnitude representation. I handle these three representation schemes in that reply, including some (not many) pros and cons

  • 1

    By the way, @Pabloalmeida, interesting reference

  • 1

    Good answer to yours. I confused the two here. Thank you for the correction. :)

  • @Pabloalmeida I also live confused. Tomorrow I probably will not remember which complement of 2 and that of 1, but today the answer is correct

Browser other questions tagged

You are not signed in. Login or sign up in order to post.