Why compiler is not giving error when signed value is assigned to unsigned integer? - C++

二次信任 提交于 2020-01-10 00:52:11

问题


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.


回答1:


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' tounsigned 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.




回答2:


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.




回答3:


-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.




回答4:


For gcc compiler you can add

gcc -Wconversion ...

And this will produce the following warning

warning: converting negative value '-0x0000000000000000a' to 'unsigned int'



回答5:


I am using g++ 4.9.2 and need to use -Wsign-conversion to make this warning appear.

gcc.gnu.org: Warnings about conversions between signed and unsigned integers are disabled by default in C++ unless -Wsign-conversion is explicitly enabled.



来源:https://stackoverflow.com/questions/765709/why-compiler-is-not-giving-error-when-signed-value-is-assigned-to-unsigned-integ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!