0

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?

Jaden
  • 45
  • 7

1 Answers1

3

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.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • 1
    It's converted to `int` *after* the subtraction, in an implementation-defined manner that happens to yield `-1`. Also, `size_t` isn't likely to be `unsigned int` on 64-bit platforms. – T.C. Sep 13 '14 at 20:59
  • Interesting. So based on the order of precedence, is it technically specified if the conversion should be performed first? – Cory Kramer Sep 13 '14 at 21:00
  • 1
    The subtraction will promote both to the unsigned integer type that is `size_t` (depending on the platform, this can be `unsigned int`, `unsigned long` or `unsigned long long`), the result is converted to an `int` in an implementation-defined manner (since it cannot be represented in `int`'s range) and used to initialize `last_index`. – T.C. Sep 13 '14 at 21:03