Here is a simplified sample. Basically, it does checks on a string from a string list. If the check passes, it will remove that string (filterStringOut(i);
), and it is no longer necessary to continue any other checks. Thus continue
to the next string.
void ParsingTools::filterStrings(QStringList &sl)
{
/* Filter string list */
QString s;
for (int i=0; i<sl.length(); i++) {
s = sl.at(i);
// Improper length, remove
if (s.length() != m_Length) {
filterStringOut(i);
continue; // Once removed, can move on to the next string
}
// Lacks a substring, remove
for (int j=0; j<m_Include.length(); j++) {
if (!s.contains(m_Include.at(j))) {
filterStringOut(i);
/* break; and continue; */
}
}
// Contains a substring, remove
for (int j=0; j<m_Exclude.length(); j++) {
if (s.contains(m_Exclude.at(j))) {
filterStringOut(i);
/* break; and continue; */
}
}
}
}
How ought one continue the outer loop from inside a nested loop?
My best guess is to use goto
and place a label at the end of the outer loop. That prompted me to ask this question, given how taboo goto
can be.
In the c++ IRC chat, it was suggested that I place the for
loops in bool functions, that return true if a check passed. thus
if ( containsExclude(s)) continue;
if (!containsInclude(s)) continue;
or that I simply create a local boolean, set it to true break
, check bool and continue if true.
Given that I am using this in a parser, I actually do need to prioritize performance in this example. Is this a situation where goto
is still useful, or is it a case where I need to restructure my code?
goto
is considered a good practice for breaking out of nested loops: https://stackoverflow.com/a/9695942/2158002 -- this is a similar but not identical situation, and for all I know, there might be a c++ feature that handles this situation. – Anon May 04 '18 at 06:21goto
, despite its bad reputation. Don't fear names - fear concepts. – Kilian Foth May 04 '18 at 06:24hasBeenRemoved
. Set it in the inner tests, but in the outer, main loop, test it before starting the next test. – user949300 May 05 '18 at 18:08