Re: goto to switch labels

From: Dave (recneps.w.divad_at_elcaro.moc)
Date: 10/05/04


Date: Tue, 05 Oct 2004 10:57:44 +0100


Eric Sosman wrote:
> Christopher Benson-Manica wrote:
>
> Here's a rearrangement that (I think) more readable:
>
> switch (i) {
> case 1:
> if (! valid1())
> goto error;
> stuff1();
> break;
> case 2:
> if (! valid2())
> goto error;
> stuff2();
> break;
> ...
> default:
> goto error;
> }
> ...
> return HOORAY_IT_FINALLY_WORKED;
>
> error:
> handle_error();
>
> (Anyone who finds the extra `goto' "inefficient"
> is invited to ponder the payoff of optimizing the error
> path, especially if the error is fatal.)
>

This would be my preference; it doesn't use a goto or negative logic,
and by specifying the value for err you could pass the reason for the
error into handl_error() if you so desired, so that the user would get a
specific error message rather than a general one that could mean
anything (which I find in my programs is more useful, even if I just
output the error number, at least I can then look in the code):

err=0;

switch (i) {
case 1:
if (valid1())
     stuff1();
else
     err=1;
break;

case 2:
if (valid2())
     stuff2();
else
     err=2;
break;

default:
err=3;
break;
}

if (err)
     handle_error(err);

Dave.



Relevant Pages