Chapter 7. Flexible Iterator Interfaces
Iterating over a set of elements is a common operation in any program. Some programming languages provide native constructs to iterate over elements, and object-oriented programming languages have guidance in the form of design patterns on how to implement generic iteration functionality. However, there is very little guidance of this kind for procedural programming languages like C.
The verb âiterateâ means to do the same thing multiple times. In programming, it usually means to run the same program code on multiple data elements. Such an operation is often required, which is why it is natively supported in C for arrays, as shown in the following code:
for
(
i
=
0
;
i
<
MAX_ARRAY_SIZE
;
i
++
)
{
doSomethingWith
(
my_array
[
i
]);
}
If you want to iterate over a different data structure, like a red-black tree, for example, then you have to implement your own iteration function. You might equip this function with data structureâspecific iteration options, like whether to traverse the tree depth-first or breadth-first. There is literature available on how to implement such specific data structures and how the iteration interfaces for these data structures look. If you use such a data structure-specific interface for iteration and your underlying data structure changes, youâd have to adapt your iteration function and all your code that calls this function. In some cases this is just fine, and even required, because you want to perform some special ...
Get Fluent 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.