I've been programming in C++ for a couples months now, and when I go through forums I've noticed a trend. It seems that goto
statements are generally regarded as being either completely wrong to use, or should only be used in very specific circumstances. What is it about goto
statements that makes them so fundamentally wrong?
The biggest reason is that it makes the code hard to follow. The goto
isn't implicitly bad; it's just easy to write hard-to-follow code with it.
For example, which would you rather read? This:
int factorial(int n) {
int result;
if(n==0 || n==1)
result = 1;
else
result = n*factorial(n-1);
return result;
}
Or this:
int factorial(int n) {
int result;
if(n > 1)
goto big;
result = 1;
goto end;
big:
result = n*factorial(n-1);
end:
return result;
}
The two implementations are the same to a machine, but the first is much clearer to our human eyes. There are times when goto
is clearer, though. For example, consider this from C (or C++ without exceptions):
void process_big_file(FILE* foo) {
if(possible_failure_1(foo))
goto cleanup;
// Do some work
if(possible_failure_2(foo))
goto cleanup;
// Do some more work
cleanup:
fclose(foo);
}
Here, using goto
makes sense because it lets you put all the cleanup code in one place, and the goto
s actually create a logical flow of execution. In particular, when reading the code, it's obvious that you always (a) reach cleanup code, and (b) always reach the same cleanup code, which is the important thing here. In the absence of exceptions, I'd actually argue that goto
is The Right Thing when trying to organize (for example) cleanup code.