The question of the cleanest way to write a loop that executes some action between each iteration has always interested me.
In a sense, what is the best way in c/c++ to implement this fictional construct:
for (...) {
} between {
}
Using such a construct you could trivially implement string join(): (pseudocode)
result = "";
foreach ( item : input ) {
result += str(item);
} between {
result += sep;
}
I have looked through some popular code libraries to see how these types of loops are implemented, and there are some common strategies:
- move the "between" code into an "if (!first/last iteration)" inside the loop.
- This is the go-to method when the index/iterator/result freely stores the notion of first/last iteration (such as checks for values of 0, .empty(), NULL etc).
- transform the "loop body" into a function and call it from two places: before and during the loop, and change the loop to skip the first element. (minor code duplication)
- This is the go-to method when the "loop body" is a single function call
Neither of these is a completely generalized solution, and while its only a few lines + a state variable, I'm trying to find an ideal solution.
Priorities:
- No needless source code duplication (but willing to accept binary code duplication)
- Efficiency
- Clear semantics
- Trivially usable (aka simple syntax, few library requirements)