Re: C++ FAQ
Francis Glassborow wrote:
The point is that using goto stops programmers exploring the
alternatives, often in the belief that those will be inferior to the
goto solution.
IMO, they should explore all the options, including goto (with its
drawbacks, of course). We're not in a world where there are just
"use goto wherever possible" and "avoid goto completely" options.
I accept that goto can be useful for machine generated code (as long
as you have no intention of trying to read and understand such code --
i.e. you are going to treat such code as some form of opaque
assembler. I also am not dogmatic that goto is necessarily bad but I
issued a challenge 18 years ago for an example of goto (in C) that
provided real benefit and have still to see one.
I don't know the details of that challenge, but I find it surprised
that you haven't seen an example, especially in C. How do you do
cleanup in case of an error in the middle of successive allocation
of resources, when there are no destructors available?
s = socket(...);
if (s < 0) goto cleanup;
r = connect(...);
if (r < 0) goto cleanupS;
f = open(...);
if (f < 0) goto cleanupS;
while (...) {
if (some error) goto cleanupF;
}
cleanupF:
close(f);
cleanupS:
close(s);
cleanup:
/* other common stuff */
return result;
Certainly you could write a goto-less version (with nested ifs or some
code duplication), but I don't see a better a better alternative here.
I don't enjoy using goto in general, but I feel no guilt as I use it
if it clearly conveys my intention and the alternatives are not as
appealing.
--
Seungbeom Kim
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]