Jaden
Jaden

Reputation: 45

what is wrong with subscript of string here in C++

This code should print "something here", but it actually print wrong

void test(){
    string str = "";
    int count = 0;
    if (count > str.length() - 1){
        cout << "something here" << endl;
        return;
    }
    cout << "wrong" << endl;
}

But, if I change a little as below, it will print "something here"

void test_2(){
    string str = "";
    int count = 0;
    int last_index = str.length() - 1;
    if (count > last_index){      // change to last_index
        cout << "something here" << endl;
        return;
    }
    cout << "wrong" << endl;
}

Anyone can help me?

Upvotes: 0

Views: 67

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117971

string::length returns a size_t which is unsigned int.

If it returns 0, and you subtract 1, it will underflow.

The reason it works in your second case is that since you say

int last_index = str.length() - 1;

The size_t is converted to int during the subtraction and assignment.

Upvotes: 3

Related Questions