I know everyone hates gotos. In my code, for reasons I have considered and am comfortable with, they provide an effective solution (ie I\'m not looking for \"don\'t do that\
The switch ... case statement is essentially a computed goto. A good example of how it works is the bizarre hack known as Duff's Device:
send(to, from, count)
register short *to, *from;
register count;
{
register n=(count+7)/8;
switch(count%8){
case 0: do{ *to = *from++;
case 7: *to = *from++;
case 6: *to = *from++;
case 5: *to = *from++;
case 4: *to = *from++;
case 3: *to = *from++;
case 2: *to = *from++;
case 1: *to = *from++;
}while(--n>0);
}
}
You can't do a goto from an arbitrary location using this technique, but you can wrap your entire function in a switch statement based on a variable, then set that variable indicating where you want to go, and goto that switch statement.
int main () {
int label = 0;
dispatch: switch (label) {
case 0:
label = some_computation();
goto dispatch;
case 1:
label = another_computation();
goto dispatch;
case 2:
return 0;
}
}
Of course, if you do this a lot, you'd want to write some macros to wrap it.
This technique, along with some convenience macros, can even be used to implement coroutines in C.