据我所知,当s2
更大时,s1.size() - s2.size()
下溢,因为它是unsigned
的减法。 为什么将它们投射到int
不会导致整数减法? 为什么要铸造整个事情给我正确的结果?我预计它会评估括号内的内容,然后下溢这会给出一个很大的数字,然后投到int
不会有什么区别。我错过了什么?为什么减法与static_cast溢出?
#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::string;
bool isShorter(const string &s1, const string &s2) {
return (static_cast<int>(s1.size()) - s2.size() < 0) ? true : false; // underflows
//return (static_cast<int>(s1.size() - s2.size()) < 0) ? true : false; // this works
}
int main() {
string s, t;
getline(cin, s);
getline(cin, t);
cout << "s: " << s << endl;
cout << "t: " << t << endl;
cout << "printing shorter string of the two..." << endl;
cout << ((isShorter(s, t)) ? s : t) << endl;
}
你缺少规则说'signed + unsigned = unsigned'。 – nwp
另外请注意,你可以做同样的事情,没有减法和铸造。 '返回((s1.size()
NathanOliver
@NathanOliver或只是'返回s1.size()
WhozCraig