Assigned gotos in standard C



To explain why I am trying to do a non-C thing in C, I am writing a
translator for a toy language targeting C.
To do this I need a way to perform assigned gotos, by which I mean I
have a number of labels LABEL_0, LABEL_0, .. LABEL_N, and wish to be
able to take an int k and do goto LABEL_k. ( I can't use function
pointers as they would be called recursively, and one soon runs out of
stack space.)

In GCC and similar, I can use the && operator to take the address of
labels, and that works fine. However I want a second solution for
those compilers that do not support this extension.
I would also like that performing the goto takes constant time, and
does not depend on the number of labels, it is to be expected that
there will be many labels.

My current solution uses setjmp/longjmp, it creates an array jmp_buf
jump_table[ size], and then initialises it by
LABEL_k : if(!setjmp( jump_table[k] ) { goto LABEL_(k+1) }
I can then go to LABEL_k by calling longjump(jump_table[k])

I have the following questions:

Is this approach correct? Not having used setjmp/longjmp before, I
want to check I'm not making some mistake.

I need that the value of one particular variable is not changed by the
longjmp, and so it can not be stored in a register. I can ensure this
by declaring it volatile, yes?

Finally, and most importantly, is there a better way to do this?
.



Relevant Pages

  • Re: change variables
    ... where goto is the most appropriate control structure in C programs. ... The C switch statement could generate a jump table to its case labels ... point of the flow is contrained to be the end of the switch block. ...
    (comp.lang.cobol)
  • Re: Colon in code?
    ... George Nicholson wrote: ... > Use of line labels and goto's is frowned upon (outside of Error ... > hyperlink definition of them via the entry for the "GoTo" statement. ...
    (microsoft.public.excel.programming)
  • Re: "GOTO considered harmful" considered harmful. Re: New style DO syntax?
    ... Fine, but then generalize the labels to be alphanumerics, perhaps terminated by a single colon. ... The main problem with goto targets in Fortran is not the GOTO, ... "GOTO considered harmful" considered harmful. ... In any case, it seems that the Fortran Standards are in the process of making block constructs more uniform, so constructive discussions here may actually have an influence. ...
    (comp.lang.fortran)
  • Re: Assigned gotos in standard C
    ... have a number of labels LABEL_0, LABEL_0, .. ... able to take an int k and do goto LABEL_k. ... Calling functions from a dispatch loop, ...
    (comp.lang.c)
  • Re: How to GOTO
    ... This means that I have need for a Forth GOTO, ... DEFERRED-LABEL is just a CELL with an address to be later ... Predeclaring labels by name is not nice when you have 50 or more labels. ... Hmm, numeric parsing labels might be okay with an extra word RESOLVE-GOTOS, ...
    (comp.lang.forth)