Next, my program keeps compiling even after I have assigned a negative value to an unsigned variable, why does this happen? Using the IDE Code :: Blocks 13.12
unsigned int numero1 = -1;
Next, my program keeps compiling even after I have assigned a negative value to an unsigned variable, why does this happen? Using the IDE Code :: Blocks 13.12
unsigned int numero1 = -1;
The assignment converts -1
, which is an int , to unsigned int .
The signed-to-unsigned conversion rule is (INT_MAX + 1) - intValue
, in this case as intValue
is -1
result is INT_MAX
If you use printf("%i", numero1)
, -1
will be displayed.
To display the correct value use printf("%u", numero1)
Source: SOen
Two things are happening:
first int implicit conversions between int and unsigned int (if you enable all compiler warnings, it is likely that it warns you that the code is kind of "strange");
Second, because the printf function accepts any type, you need to manually specify how you want to display the value, with% d (which is equal to% i in printf but not in scanf) or% u (again, if you enable all the warnings of the compiler it may be that it warns you of the incongruity between the declaration and printf, depending on the compiler version)
Is unsigned useless? Well, it has its purpose, but it's true that for error checking it does not do it!
For example, if you do
unsigned int numero1 = 1 - 2; // Dá -1, mas vai ser convertido para unsigned
if(numero1 < 0){ // nunca será true
// ...
}
You will have a beautiful and useless if which will never run because the condition is always false (the result of the operation being interpreted as a pretty large positive number), but if you take out the unsigned the if will work (the same bit pattern inside the computer will be interpreted as -1).
Probably the compiler is removing the signal and only assigning the value 1
to the variable, make a printf
of this variable to take the test. when the print is done with %u
the bit representing the value is negative / positive and will be considered part of the digit will soon generate a gigantic number 4294967291
when performing print with '% i' will be disregarded. consider the last digit as the representative of the type of the number (negative / positive).