How to create a jump table in c or c++ ?

A

Andreas

Hi,

can someone tell me how i do create a jump table in c or c++ ?
I tried this:

void f()
{
void *jump_table[] =
{
label1,
label2
};

goto jump_table[1];

label1:
// some code ...
label2:
// some code ...
}

It doesn't work,
the compiler (VC6) refuses to assign the labels to the array.
Please help me !

Andreas
 
R

Ron Natalie

Andreas said:
Hi,

can someone tell me how i do create a jump table in c or c++ ?
I tried this:

You can't get the address of a label. Your options are to either use
functions and an array of function pointers, or use a switch statement.

It looks like in your case a switch statement is what you are looking
for:
void f() {
switch(1) {
case 1:
// some code...;
case 2:
// some code...
}
}

In actuallity, the given a reasoable ratio of the number of labels to the
range of choices most
compilers will generate a jump table out of that code (otherwise it tends to
devolve into the
logical equivelent of a bunch of if() statement). I checked in the g++
code once for the threshold
for making that decision and it almost always favors making the jump table.
You have to do something
really bizaare like:

switch(i) {
case 1: // code.
case 425824356: // code
}
to force it the other way.
 
V

Victor Bazarov

Andreas said:
can someone tell me how i do create a jump table in c or c++ ?

No such thing in either language, I'm afraid. You cannot have
an array of labels.

You can, however, create and use a _call_ table. All you need
is an array of pointers to functions, and then call the indexed
one:

void f1() {
// do something
}

void f2() {
// do something else
}

void f() {
void (*ptrs[])() = { f1, f2 };
ptrs[1](); // calls f2
}
I tried this:

void f()
{
void *jump_table[] =
{
label1,
label2
};

goto jump_table[1];

label1:
// some code ...
label2:
// some code ...
}

It doesn't work,
the compiler (VC6) refuses to assign the labels to the array.

And so will every sane C++ compiler on the planet.

Victor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,156
Messages
2,570,878
Members
47,408
Latest member
AlenaRay88

Latest Threads

Top