Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.

# How To Represent Boundaries With Pointers

June 25, 2014

Let's continue last week's discussion about the relationship between boundaries and pointers. We had gotten as far as defining two types, which we called pointer and boundary types, with each type having before and after operations. Applying either of these operations to a pointer yields a boundary, and vice versa.

Two weeks ago, we suggested that if lower and upper are boundaries that define a range of elements in a sequence, we can process those elements by writing code along the following lines:

b = lower;
while (b != upper) {
// Process the element immediately to the right of b
++b;
}

As we have already noted, computer hardware normally gives us pointers, not boundaries; C++ reflects this hardware preference. Accordingly, we would like to rewrite this code to use pointers instead of boundaries.

Let's start by defining begin and end as pointers that define the same range as lower and upper. To do so, we will use the convention we established last week, where the pointer that corresponds to a boundary points to the element immediately after the boundary:

begin = after(lower);
end = after(upper);
p = begin;

while (p != end) {
// Process the element pointed to by p
++p;
}

The key point in this code is that in the original version, "the element immediately to the right of b" is the same as after(b). Therefore, because begin is after(lower), and p starts out with the same value as begin, the first time through the loop, the element to process is the one to which p points. Once we have made this observation, the rest of the code follows.

In other words, once we have adopted the convention that in order to convert a boundary to a pointer, we move in a particular direction to find the element to which to point (i.e., using after(b) rather than before(b)), we have done all that is necessary to take the symmetric code that uses boundaries and convert it to asymmetric code that uses pointers. The asymmetry comes from the fact that to turn a boundary into a pointer, we must move in one direction or the other.

Next week, we shall explore the effect that this forced asymmetry has on the design of reverse iterators in the C++ standard library.

### More Insights

 To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.