1

I have the code below:

string s = "haha";
cout << s << endl; //haha
cout << s.length() << endl; //4
cout << (s[25] == 'h' ? "is h" : "is not h") << endl; //is not h
cout << s[0] << endl; // h
cout << s[25] << endl; // nothing...blank

It seems that pointing to any index even if it is out of range does not throw any error...what is the reason?

Dumbo
  • 13,555
  • 54
  • 184
  • 288
  • 3
    C++ doesn't do any bounds checking on itself. You'll need to know what you're doing. – PMF Aug 10 '15 at 11:29
  • 3
    @PMF: It does, but only if you tell it to. Accessing an invalid index through `[]` is *undefined behaviour*. Which means the behaviour is not defined to give an error message, throw an exception, or crash the program. It *could*, but it doesn't have to, so implementations don't have to do the additional bounds check -- speeding things up. Accessing through `at()` *is* defined to throw an exception if the index is invalid. – DevSolar Aug 10 '15 at 11:29
  • To answer your question of "what is the reason" https://stackoverflow.com/questions/1239938/c-accesses-an-array-out-of-bounds-gives-no-error-why – Cory Kramer Aug 10 '15 at 11:33

4 Answers4

8

Efficiency. You can use at function for bounds check.

ForEveR
  • 55,233
  • 2
  • 119
  • 133
2

Class string provides bound checking in at function, it throws exception if the subscript is invalid.

Nishant
  • 1,635
  • 1
  • 11
  • 24
2

The std::string::operator[] documentation says:

char& operator[] (size_t pos);

Exception safety

If pos is not greater than the string length, the function never throws exceptions (no-throw guarantee). Otherwise, it causes undefined behavior.

sergej
  • 17,147
  • 6
  • 52
  • 89
1

in document of stl strings, the part regarding operator[] in here it is mentioned that (It is for string s, at position pos, s[pos])

Exception safety If pos is not greater than the string length, the function never throws >exceptions (no-throw guarantee). otherwise, it causes undefined behavior.

one interesting point is that:

If pos is equal to the string length, the function returns a reference to a >null character ('\0').(C++98)

If pos is equal to the string length, the function returns a reference to >the null character that follows the last character in the string, which >shall not be modified.(C++11)

but member function ".at" is as it says in documents:

Strong guarantee: if an exception is thrown, there are no changes in the >string.

If pos is not less than the string length, an out_of_range exception is >thrown.

Community
  • 1
  • 1
FazeL
  • 916
  • 2
  • 13
  • 30