Consider:
unsigned foo(unsigned u) {
return u;
}
int main() {
foo(-1);
return 0;
}
Here, the function foo
is called with u
equal to 4294967295 (or a similar large value.) If the programmer wasn't paying attention, this might be quite unexpected.
For instance, maybe you are implementing pow
to raise your Polynomial class to a power. Since only positive powers are possible, you decide on the signature
Polynomial pow(const Polynomial& p, unsigned exp);
Then a careless programmer calls pow(p, -1)
to get an inverse and, rather than a warning or error, it appears to work, but probably uses an extreme amount of memory and time to produce a totally wrong answer.
g++ 5.3.0, and gcc 5.3.0, compile this without complaint with -Wall -Wextra
.
They will warn about it with the option -Wsign-conversion
, but this warns about every conversion from int
to unsigned
and is rapidly too annoying (it warns every time you index into a vector with an int
, vec[i]
, for example.)
Can gcc warn just about passing a negative literal, or other negative compile-time constant, as an unsigned parameter?