I was making a "concatenating iterator", i.e. an iterator that would iterate over the ints in an int**.
Its constructor needs:
- An array of
T**, representing the beginning of each sub-array. - An array of
T**, representing the end of each sub-array.
Lo and behold, I ran across a situation where goto seemed to be appropriate.
But something within me screamed "NO!!" so I thought I’d come here and ask:
Should I try avoid goto situations like this? (Does it improve the readability if I do?)
#include <algorithm>
template<class T>
class lazy_concat_iterator
{
// This code was meant to work for any valid input iterator
// but for easier reading, I'll assume the type is: T**
mutable T** m_endIt; // points to an array of end-pointers
mutable T** m_it; // points to an array of begin-pointers
mutable bool m_started; // have we started iterating?
mutable T* m_sub; // points somewhere in the current sub-array
mutable T* m_subEnd; // points to the end of the current sub-array
public:
lazy_concat_iterator(T** begins, T** ends)
: m_it(begins), m_endIt(ends), m_started(false) { }
void ensure_started() const
{
if (!m_started)
{
m_started = true;
INIT:
m_sub = *m_it;
m_subEnd = *m_endIt;
if (m_sub == m_subEnd) // End of this subarray?
{
++m_it;
++m_endIt;
goto INIT; // try next one <<< should I use goto here?
}
}
}
};
How you could use it:
#include <vector>
#include <cstring>
using namespace std;
int main(int argc, char* argv[])
{
vector<char*> beginnings(argv, argv + argc);
vector<char*> endings;
for (int i = 0; i < argc; i++)
endings.push_back(argv[i] + strlen(argv[i]));
lazy_concat_iterator<char> it(&beginnings[0], &endings[0]);
it.ensure_started(); // 'it' would call this internally, when dereferenced
}
Yes, you can and should avoid
goto, for example this code should do the equivalent for what yours does from theINITlabel (this also works for input iterators which was a “hidden requirement” as it doesn’t dereferencem_itandm_endItan extra time once the condition is met unlike my previous transformation):Previous answer attempt:
Even a forever loop would be clearer and neater than a
goto. It highlights the obvious “never terminate” possibility even better.Although I don’t see why you need to assign to
m_subEndandm_subItinside the loop. If you don’t you can rewrite this as a while loop: