i was writing this code and faced this unknown behavior.
void solve(){
string s = "a";
for(int i = 0; i < s.size() - 1; i++){
cout << "1st for loop\n";
if(s[i] == s[i + 1]){
cout << s[i] << s[i + 1] << '\n';
return;
}
}
for(int i = 0; i < s.size() - 2; i++){
cout << "2nd for loop " << i << '\n';
if(s[i] != s[i + 1] and s[i] != s[i + 2] and s[i + 1] != s[i + 2]){
cout << s[i] << s[i + 1] << s[i + 2] << '\n';
return;
}
}
cout << -1;
}
shouldn't it print -1? then why it enters into second for loop as the size of my string is 1? Can anyone help me to understand this behavior?
string.size ()
returns unsigned integer. So the negative number you get from subtractings.size()
by2
converts to a very large number.thanks a lot for making it clear :)
std::string::size()
returnsstd::size_t
, which is an unsigned type (usuallyunsigned long long
).If
std::size_t
isunsigned long long
, then:When
s.size() == 0
,(int)s.size() - 1
becomes18446744073709551615
,(int)s.size() - 2
becomes18446744073709551614
.When
s.size() == 1
,(int)s.size() - 2
becomes18446744073709551615
.Try:
change
i < s.size() - 1
toi < (int)s.size() - 1
change
i < s.size() - 2
toi < (int)s.size() - 2
Another better way is to define
int n = (int)s.size()
and replace everys.size()
withn
.thanks thanks a lot for detailed clarification :)
Try using int n = (int)s.size();