Iterators and Traversal Patterns in C
Post 10 of the Dynamic Arrays in C series · Full source code on GitHub The Loop You Write a Hundred Times Every program that uses an array eventually writes the same loop. Create an index variable. Check it against the size. Access the element. Increment. Repeat. For our dynamic array, that loop looks like this: 1 2 3 4 for (size_t i = 0; i < array_size(arr); i++) { int *val = (int *)array_get(arr, i); process(*val); } Five lines, two function calls per iteration, and a cast. It works. It has worked since K&R. And it has three problems that compound as codebases grow. ...