This section describes the operators that can have pointers as operands and how these operators are used with pointers. C++ enables pointer arithmetic—a few arithmetic operations may be performed on pointers. Pointer arithmetic is appropriate only for pointers that point to built-in array elements.
A pointer may be incremented (++
) or decremented (--
), an integer may be added to a pointer (+
or +=
) or subtracted from a pointer (-
or -=
), or one pointer may be subtracted from another of the same type—this particular operation is appropriate only for two pointers that point to elements of the same built-in array.
Portability Tip 8.2
Most computers today have four-byte or eight-byte integers. Because the results of pointer arithmetic depend on the size of the objects a pointer points to, pointer arithmetic is machine dependent.
Assume that int v[5]
has been declared and that its first element is at memory location 3000
. Assume that pointer vPtr
has been initialized to point to v[0]
(i.e., the value of vPtr
is 3000
). Figure 8.15 diagrams this situation for a machine with four-byte integers. Variable vPtr
can be initialized to point to v
with either of the following statements (because a built-in array’s name evaluates to the address of its zeroth element):
int *vPtr = v;
int *vPtr = &v[ 0 ];
3.143.4.181