Is there any difference?

Hey guys,

I've been using the member function ".at" of the String object for printing out character positions in a string. This book I'm reading though uses a simple array search I'm guessing like this "[0]".

I've wrote an example below, I'm just curious whether there's any difference between the two.

Thanks.

1
2
3
  string word = "bob";
    cout << "Character at position 2: " << word.at(2); // The way I wrote
    cout << "Chracter at position 2: " << word[2]; // Book way 
at() does bounds checking, and will throw an exception if you access an index outside the range of the string. The array subscript operator (that's what operator[] is called) does not do this check, so you can invoke undefined behavior without an error. In debug modes, though, I'd think even the array subscript operator would do a check for you though.
Ah yes that makes sense. It's just explained exactly what you just said in this book.

Is one way better or more efficient than the other? Especially if you're working with large string objects?

Because later on, I used the .at member function to change the first char value. I'm curious as to if one or the other finds characters differently?

1
2
gameOver.at(0) = 'F'; //The way I wrote
gameOver[0] = 'F'; // Book way 


Thanks for your help.
Topic archived. No new replies allowed.