We had a bug in our code coming from the line
unsigned int i = -1;
When the code was originally written, is was i = 0
and thus correct.
Using -Wall -Wextra
, I was a bit surprised that gcc didn't warn me here because -1 does not fit in an unsigned int.
Only when turning on -Wsign-conversion
this line becomes a warning - but with it many many false positives. I am using a third party library which does array-like operations with signed int's (although they cannot be < 0), so whenever I mix that with e.g. vector, I get warnings - and I don't see the point in adding millions of casts (and even the 3rd party headers produce a lot of warnings). So it is too many warnings for me. All these warnings are that the conversion "may change the sign". That's fine because I know it doesn't in almost all of the cases.
But with the assignment mentioned above, I get the same "may change" warning. Shouldn't this be "Will definitely change sign!" instead of "may change"? Is there any way to emit warnings only for these "will change" cases, not for the maybe cases?
Initialize it with curly braces :
unsigned int i{-1};
GCC outputs :
main.cpp:3:22: error: narrowing conversion of '-1' from 'int' to 'unsigned int' inside { } [-Wnarrowing] unsigned int i{-1};
Note that it does not always cause an error, it might be a warning or disabled altogether. You should try it with your actual toolchain.
But with the assignment mentioned above, I get the same "may change" warning. Shouldn't this be "Will definitely change sign!" instead of "may change"?
That's odd. I tested a few versions of gcc in the range of (4.6 - 5.2) and they did give a different warning for unsigned int i = -1;
warning: negative integer implicitly converted to unsigned type [-Wsign-conversion]
That said, they are indeed controlled by the same option as the may change sign warnings, so...
Is there any way to emit warnings only for these "will change" cases, not for the maybe cases?
As far as I know, that's not possible. I'm sure it would be possible to implement in the compiler, so if you want a separate option to enable the warning for assigning a negative number - known at compile time - to an unsigned variable, then you can submit a feature request. However, because assigning -1
to an unsigned variable is such a common and usually perfectly valid thing to do, I doubt such feature would be considered very important.
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