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

后端 未结 5 1430
说谎
说谎 2020-12-16 12:09

I know unsigned int can\'t hold negative values. But the following code compiles without any errors/warnings.

unsigned int a = -10;
<
相关标签:
5条回答
  • 2020-12-16 12:44

    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.

    0 讨论(0)
  • 2020-12-16 12:50

    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.

    0 讨论(0)
  • 2020-12-16 12:52

    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.

    0 讨论(0)
  • 2020-12-16 12:59

    For gcc compiler you can add

    gcc -Wconversion ...
    

    And this will produce the following warning

    warning: converting negative value '-0x0000000000000000a' to 'unsigned int'
    
    0 讨论(0)
  • 2020-12-16 13:10

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

    0 讨论(0)
提交回复
热议问题