Let’s consider another application of pointer-to-functions, Jump tables! **A jump table is a special array of pointer-to-functions. Since, this is an array, and as we know that all array elements must be of same type, therefore, it requires that all functions must be of same type and all take same number and same type of parameters. Further, this technique can be used where different tasks could be represented by consecutive integers beginning with zero.**

**The another trick is to make sure that all function prototypes appear before jump table declaration.** First step to create a jump table is to declare and initialize the jump table. For example,

/* function prototypes */ int add(int, int); int sub(int, int); int mul(int, int); int divide(int, int); /*jumptable declared and initialized */ int (*diff_oper[])(int, int) = {add, sub, mul, divide};

Then, call the operation in jumptable, providing values to arguments,

result = diff_oper[(operator)](op1, op2);

/* jumptables.c -- program shows how jumptable is used to perform basic * calculator functions */ #include <stdio.h> #define ADD 0 #define SUB 1 #define MUL 2 #define DIV 3 int add(int, int); int sub(int, int); int mul(int, int); int divide(int, int); int main(void) { int op1, op2; int result; char operator; /*jumptable declared and initialized */ int (*diff_oper[])(int, int) = {add, sub, mul, divide}; puts("**Calculator Application**"); result = diff_oper[(ADD)](50, 20); printf("ADD of %d and %d is: %d\n", 50, 20, result); result = diff_oper[(SUB)](50, 20); printf("SUB of %d and %d is: %d\n", 50, 20, result); result = diff_oper[(MUL)](50, 20); printf("MUL of %d and %d is: %d\n", 50, 20, result); result = diff_oper[(DIV)](50, 20); printf("DIV of %d and %d is: %d\n", 50, 20, result); return 0; } int add(int a, int b) { return a + b; } int sub(int a, int b) { return a - b; } int mul(int a, int b) { return a * b; } int divide(int a, int b) { return a / b; }

Output turns out as,

**Calculator Application** ADD of 50 and 20 is: 70 SUB of 50 and 20 is: 30 MUL of 50 and 20 is: 1000 DIV of 50 and 20 is: 2

How about if u need to perform some 50, 100 different operations. Jumptable is wonderful, then! If you think you can do the same job using switch statement, of course, you can. But switch statement, then, would go very large.

Notice that above program could be modified to make more interacting one. So, wouldn’t you like to try?

**Sanfoundry Global Education & Learning Series – 1000 C Tutorials.**

**If you find any mistake above, kindly email to [email protected]**

**Related Posts:**

- Apply for Computer Science Internship
- Check Computer Science Books
- Watch Advanced C Programming Videos
- Check C Books
- Practice Computer Science MCQs