In C++, is it bad to use string[x] to get a char at a specific location?
Most people use string.at(x) but is there a reason why string[x] is bad?
1 Answer
As far as I'm aware most people don't use string.at(). If your code is well written and well understood, you should always be working within the bounds of your string so don't need the run-time bounds checking that string.at() provides. Same goes for the other sequence containers with .at().
2 Comments
syam
In addition, random access in strings is seldom required, the vast majority of string operations can be performed using sequential access (ie. using iterators instead of indexes). Same goes with other sequence containers.
Pete Becker
+1 for designing code to work correctly rather than adding random hacks to catch mistakes.
string.at()?