5

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?

2
  • 3
    Most people use string.at()? Commented Oct 8, 2013 at 4:14
  • The real question is not "whether one is better or worse", but "what's the difference and when to use each". Commented Oct 8, 2013 at 4:32

1 Answer 1

10

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().

Sign up to request clarification or add additional context in comments.

2 Comments

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.
+1 for designing code to work correctly rather than adding random hacks to catch mistakes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.