Running this code:
#include <string>
#include <iostream>
using namespace std;
int main() {
string a = "Hello, world!";
cout << (-1)*a.size() << endl;
}
I get:
18446744073709551603
which is clearly not what I want. This annoying bug happens every time I try to multiply a string::size() by a negative number (but not for positive!). I can’t figure out what is the problem here.
In
(-1)*a.size(),(-1)has typeintanda.size()has an unsigned type (probablysize_t).(-1)*a.size()is computed as an unsigned integer, because promotion and conversion rules favor unsigned types when binary operations are applied to a signed type and an unsigned type.