I know unsigned int can't hold negative values. But the following code compiles without any errors/warnings.
unsigned int a = -10;
When I print the variable a, I get a wrong value printed. If unsigned variables can't hold signed values, why do compilers allow them to compile without giving any error/warning?
Any thoughts?
Edit
Compiler : VC++ compiler
Solution
Need to use the warning level 4.
Conversion from signed to unsigned does not necessarily just copy or reinterpret the representation of the signed value. Quoting the C standard (C99 6.3. 1.3): When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
The Problem then your compiler may issue a warning like "comparison between signed and unsigned integer expressions". Briefly, the problem is that a standard C++ compiler will handle this code by casting x as an unsigned int before doing the comparison, which may turn a negative number into a large positive number.
It will show as a positive integer of value of max unsigned integer - 4 (value depends on computer architecture and compiler).
You simply cannot assign a negative value to an object of an unsigned type. Any such value will be converted to the unsigned type before it's assigned, and the result will always be >= 0.
warning C4245: 'initializing' : conversion from 'int' to 'unsigned int', signed/unsigned mismatch
On warning level 4.
Gives me the warning:
warning: converting of negative value
-0x00000000a' to
unsigned int'
Without any -W directives.
You must use:
gcc main.c -Wconversion
Which will give the warning:
warning: negative integer implicitly converted to unsigned type
Note that -Wall will not enable this warning.
Maybe you just need to turn your warning levels up.
Converting a signed int
to an unsigned int
is something known in the C standard as a "Usual arithmetic conversion", so it's not an error.
The reason compilers often don't issue a warning on this by default is because it's so commonly done in code there would be far too many 'false positive' warnings issued in general. There is an awful lot of code out there that works with signed int
values to deal with things that are inherently unsigned (calculating buffer sizes for example). It's also very common to mix signed and unsigned values in expressions.
That's not to say that these silent conversions aren't responsible for bugs. So, it might not be a bad idea to enable the warning for new code so it's 'clean' from the start. However, I think you'd probably find it rather overwhelming to deal with the warnings issued by existing code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With