I've been trying to learn what exactly jump tables are, and I'm having trouble understanding something. From the many examples I've seen they seem to pretty much boil down to this, or at least this is one version of it:
void func1() {};
void func2() {};
void func3() {};
int main()
{
void(*jumpTo[3])(void) = { func1, func2, func3 };
jumpTo[1]();
return 0;
}
These just appear to be an array of function pointers, that are indexed by a certain value/position. Is it the case then that a jump table is just indexing an array of function pointers? I'm really curious about this because I've seen a lot of people saying that switch statements are often compiled into jump tables as a performance measures. From my understanding, by jumping to a function in this way it involves a pointer dereference and a function call. I thought that both of these weren't that great for performance.
Another answer on this site said that by doing it this way "you are adding a function call overhead that a switch statement doesn't necessarily have." How would a switch that compiles to a jump table avoid function calls?
Also, a highly voted answer here said "A jump table can be either an array of pointers to functions OR an array of machine code jump instructions." How would you jump to machine code instructions instead of dereferencing a pointer? Is this faster?
Is the difference between the two that in my above example the pointer doesn't have to be dereferenced because it can be statically bound? As opposed to passing in a random number as index at runtime?
Thanks.
A jump table and your function table are basically the same - an array of addresses. A jump table contains addresses of
goto
- targets. The only difference between both is how the jump is made. When a function is called the return address is pushed on the stack, so when the function terminates it can return.Here an example of a jump table:
This compiles to: