Chapter 5. Pointer Arithmetic

The pointer arithmetic that C++ inherited from C allows you to calculate any value whatsoever, use it as a pointer (to int, double, or any other type) and read from that portion of memory—or even worse, write into it. Actually, pointer arithmetic is just another syntax to access memory the way an index does in the array, and the consequences are exactly the same, as discussed in Chapter 4. The difference is that, in case of a vector accessed via an index, we can write our own [] operator with a sanity check, whereas in pointer arithmetic we cannot.

Therefore, the advice here is very simple: do not use pointer arithmetic. There is nothing you can do with it that you cannot do with a vector and an index. In fact, in Chapter 6 we’ll see that sometimes indexes work where pointers don’t. So avoid pointer arithmetic. It is evil.

Rule for this chapter to avoid errors in pointer arithmetic:

  • Avoid pointer arithmetic. Use template vector or array with index instead.

Get Safe C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.