for (...) {
if (...) {
//do things
goto h;
}
}
h:
//do more things
Is the h block going to execute even if the goto in the upper section doesn't?
-note: I have heard that goto is 'bad form', but this is really a perfect use for it, and unless someone can present me with substantive proof that it has some secret memory leak or something terrible like that, then I really don't care.
-note: I have heard that goto is 'bad form', but this is really a perfect use for it, and unless someone can present me with substantive proof that it has some secret memory leak or something terrible like that, then I really don't care.
"I don't know what this does, but I'm going to do it!" You'll get far with that attitude.
The code as presented is precisely equivalent to:
1 2 3 4 5 6 7
for (...) {
if (...) {
//do things
break;
}
}
//do more things
In your case you have an if inside a for loop. The break statement exits the most recently entered loop, which in this case means it breaks out of the for loop (in the process also exiting the if statement, but this is irrelevant because ifs don't affect break).
// Example program
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
cout << i;
}
cout << "Hello!";
return 0;
}
As a side note, one of my professors who is a C++ guru (idk if I should really say guru but he has worked in industry) said that you should also evade break and continue statements because they act like gotos. Is that really true? Should breaks and continues be avoided?
break, continue and goto are are three different forms of jump statements.
They are birds of a feather; avoid them if more elegant alternatives are available.