jump tables (was Re: Why no labelled loops?)

chris at mimsy.UUCP chris at mimsy.UUCP
Sun Mar 1 11:15:58 AEST 1987


In article <545 at mntgfx.MENTOR.COM> franka at mntgfx.MENTOR.COM (Frank A.
Adrian) writes:
>Now for my pet peeve.

(Well, *he* spells it right. :-) )

>Why can't you take the address of a label?

Actually, due to what must be considered a bug in 4BSD PCC, you can:

	f()
	{
		int *p;

		/* esablish label name: */
		if (0) goto foo;
		p = foo;
		...

There is a hitch, however:  You cannot `goto p'.  If you are willing
to cheat, it is possible.  See the appended bug ... I mean program.

>[A jump table] is different [from `switch'] in three ways ...

All true enough.

>This construct is not difficult to implement on linkers,

Also true.

>it is not any more hazardous than the goto statement itself,

Not so!  The existing C `goto' can never change function contexts.
Only `longjmp' has this power.  Label assignments, unless they are
severely restricted, one can do non-local `goto's quite easily.
This also means that the label type must carry around a lot of
extra baggage, which has a tendency to destroy much of the efficiency
you thought you were gaining.

>and it introduces a capability into the language which is not
>currently there and for which no fast workaround exists.

True.

>In fact, I wonder why this idea has not been implemented before...

I think it has.

/*
 * Program demonstrating weird jump table.
 *
 * Passes lint.
 */
int *labels[3];

main()
{
	register int *addr;	/* r11 */
	register int i;

#ifdef lint
#define	LABEL(i, l) if (rand()) goto l; else labels[i] = l
#else
#define LABEL(i, l) if (0) goto l; else labels[i] = l
#endif

	LABEL(0, foo);
	LABEL(1, bar);
	LABEL(2, baz);

	i = 0;
loop:
	if (i < 3) {
		addr = labels[i++];
#ifdef lint
		addr = addr;
#endif
		asm("	jmp	(r11)");
		printf("oops\n");
		exit(1);
	}
	printf("done\n");
	exit(0);

foo:
	printf("foo\n");
	goto loop;

bar:
	printf("bar\n");
	goto loop;

baz:
	printf("baz\n");
	goto loop;
}
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7690)
UUCP:	seismo!mimsy!chris	ARPA/CSNet:	chris at mimsy.umd.edu



More information about the Comp.lang.c mailing list