LM10xLeoMessi's blog

By LM10xLeoMessi, history, 4 hours ago, In English

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?

  • Vote: I like it
  • 0
  • Vote: I do not like it

»
4 hours ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

string.size () returns unsigned integer. So the negative number you get from subtracting s.size() by 2 converts to a very large number.

  • »
    »
    3 hours ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    thanks a lot for making it clear :)

»
4 hours ago, # |
Rev. 5   Vote: I like it 0 Vote: I do not like it

std::string::size() returns std::size_t, which is an unsigned type (usually unsigned long long).

If std::size_t is unsigned long long, then:

When s.size() == 0, (int)s.size() - 1 becomes 18446744073709551615, (int)s.size() - 2 becomes 18446744073709551614.

When s.size() == 1, (int)s.size() - 2 becomes 18446744073709551615.

Try:

change i < s.size() - 1 to i < (int)s.size() - 1

change i < s.size() - 2 to i < (int)s.size() - 2

Another better way is to define int n = (int)s.size() and replace every s.size() with n.

void solve(){
    string s = "a";
    n = (int)s.size();
    for(int i = 0; i < n - 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 < n - 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;
}
»
2 hours ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

Try using int n = (int)s.size();