Unsigned modifier for integer type in C

3

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);
}

It simply accepts negative value and displays the value 4294967293 , the compiler should not I have said that this value would not be allowed to be stored?

    
asked by anonymous 02.10.2016 / 16:47

1 answer

2

No, C does not work that way. 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 good response here on the site that are wrong because they confuse it.

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, very much so that it is the intention to have that value. C is weakly typed for allowing implicit coercion. That is, it takes a placeholder for the data, applies a type in it and considers that the data that is there is of that type, it does not matter if that was the intention.

This gives you flexibility and performance help in a variety of situations. But it reduces robustness, a feature that C has never attempted to have.

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

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

Related: Using Data Type Modifiers

    
02.10.2016 / 16:59