Unsigned modifier for integer type in C

Asked

Viewed 51 times

4

The works say that this modifier causes the variable not to accept negative values, but when I compile this code:

#include <stdio.h>
void main()
{

    unsigned int idade;
    idade = -3;    /* Não existe idade negativa */
    printf("Idade digitada : %u\n",idade);
}

He simply accepted the negative value provided and displays in the console the value 4294967293, compiler should not have said that this value would not be allowed to be stored?

1 answer

3


No, C doesn’t work like that. C is a language designed to be a higher-level assembly. So the language should allow the user to do unsafe things.

C is a weakly typed language. Not to be confused with dynamically typed. Most programmers confuse this and have quite a well-voted response here on the site that are wrong because they confuse this.

Data and variables must have a type defined at compile time, so C is statically typed. But there is no guarantee that the value is adequate, let alone that it is the intention to have that value. C is weakly typified by allowing implicit coercion. That is, he takes a space reserved for the dice, applies a type to it and considers that the data that is there is of that type, no matter if the intention was that.

This gives flexibility and performance help in many situations. But it reduces robustness, a feature C has never tried to have.

Some compilers provide the possibility to connect a Warning to warn that this is occurring. It is not part of the standard and should be optional. An example is -Wconversion of the GCC.

Something similar has already been answered in How -1 can be greater than 4?.

Related: Use of data type modifiers

  • Thanks for the clarification!

Browser other questions tagged

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