views:

624

answers:

4

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.

A: 

For gcc compiler you can add

gcc -Wconversion ...

And this will produce the following warning

warning: converting negative value '-0x0000000000000000a' to 'unsigned int'
Mykola Golubyev
+13  A: 

Microsoft Visual C++:

warning C4245: 'initializing' : conversion from 'int' to 'unsigned int', signed/unsigned mismatch

On warning level 4.

G++

Gives me the warning:

warning: converting of negative value -0x00000000a' to unsigned int'

Without any -W directives.

GCC

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.

GMan
Yes that's the issue. I made the warning level up and I am getting warning now.
Appu
-Wall doesn't show, does it?
Mykola Golubyev
Ah, you are right. I edited my post with the correct information. I used g++ because he was using C++, and it turns out g++ doesn't even need -Wall or -Wconversion. However, when using just GCC, you do need -Wconversion (not -Wall) like you suggested.Thanks :)
GMan
+2  A: 

-10 is parsed as an integer value, and assigning int to unsigned int is allowed. To know you are doing something wrong the compiler has to check whether your integer (-10) is negative or positive. As it is more than a type check, I guess it has been disabled for performance issues.

Ben
+4  A: 

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.

Michael Burr
+1, thorough explanation.
j_random_hacker