I see a lot of hate for goto, a lot of places saying never to use it in your code no matter the circumstance, and a lot of languages that despite being procedural decide to completely omit the feature. There was a python module written as an April fool's day joke that implemented goto, but urged the reader to never actually use it for anything. Java treats it as a syntax error. People say that it should be avoided because it makes code harder to read and can always be replaced with structured code.
Is it that bad?
Often I find times that I want to interleave iterations of a loop with a certain operation, and this is a chore without duplicating code or introducing otherwise pointless variables.
Because of that, I find this type of code (focus on the "goto") acceptable:
#include <iostream>
#include <vector>
std::string join(std::vector<std::string> const vec, std::string const sep) {
if (vec.size() == 0) return "";
std::string result;
auto pos = vec.begin(), end = vec.end();
goto skip_separator;
while (pos != end) {
result += sep;
skip_separator:
result += *pos++;
}
return result;
}
int main() {
std::vector<std::string> vec {"a", "test", "string"};
std::cout << join(vec, " ") << std::endl;
return 0;
}
I want to know what other programmers think: is a "goto" here called for? Does it clarify or does it obscure? Consider the alternatives (duplicating the latter half of the loop body above the loop, or introducing a new variable and an if statement into the loop), are they more or less readable or expressive in your opinion? If the goto is to be avoided, which of the alternatives is preferred? Can you add a condition but have it reliably optimized out by -funswitch-loops?
What do you think?