A goto statement is never necessary in a language that has a minimal
set of structured control constructs (there's a theorem to that
effect), but it *can* be useful at times.
For example:
Crappy design:
void foo(void)
{
foo_type *foo = NULL;
bar_type *bar = NULL;
baz_type *baz = NULL;
foo = init_foo_type(); /* returns NULL on error */
if (foo == NULL) goto ERROR;
bar = init_bar_type();
if (bar == NULL) goto ERROR;
baz = init_baz_type();
if (baz == NULL) goto ERROR;
/*
* A bunch of code that uses foo, bar, and baz.
*/
ERROR:
if (baz != NULL) cleanup_baz_type(baz);
if (bar != NULL) cleanup_bar_type(bar);
if (foo != NULL) cleanup_foo_type(foo);
}
The same without goto:
if ((foo = init_foo_type())
&& (bar = init_bar_type())
&& (baz = init_baz_type())
) {
/* work */
}
cleanup_baz_type(baz);
cle......
or avoiding the big if and breaking the whole work down into different
levels, hiding too much details but giving better overview of the real
work:
static int init_types(int **foo, int **bar, int **baz) {
return (*foo = init_foo_type())
&& (*bar = init_bar_type())
&& (*baz = init_baz_type());
}
static void cleanup_types(.... like init_types but cleanup.......
:
:
:
void foo(void) {
foo_type *foo = NULL;
bar_type *bar = NULL;
baz_type *baz = NULL;
if (init_types(&foo, &bar, &baz)) {
do_work(....);
}
cleanup_types(&foo, &bar, &baz);
}
I would prefere the second choice when runtime is not really critical
because it makes anything more maintenanceable and more readable.
Of course it could be restructured. The most obvious way to do so is
to use nested if statements, with the nesting level becoming deeper as
the number of initializations increases. Another approach is to
replace each "goto ERROR;" with a return statement; the second and
third would have to be preceded by cleanup calls.
I would reduce the number of if statements and increasing the
readability, and the time testing is needed. When init is tested well
it can be ignored easy during forthgoing debug becaus it is known as
ready for GA. The same is for the real work......
I like to hide so much details as possible because it is after 3 years
untouched sources more easy to extend or even change the functionality
when details are hidden until there is a real need to know about them.
So looking at WHAT is going on and looking on HOW is it done only when
there is a need for makes anything much easier to understund.
--
Tschau/Bye
Herbert
Visit
http://www.ecomstation.de the home of german eComStation
eComStation 1.2 Deutsch ist da!