In an interview I was asked to write an efficient program such that for each integer value given, a function is called.
For example: if user enters 1 then function one
will get executed if user enters 5 then function five
gets executed and so on..
I was not able to come up with an efficient idea, like we can't use an if statement for checking the value entered and then executing the corresponding functions.
Is there any way we can do this in an efficient manner?
One of the option would be using function pointers, as below.
Declares a type of a void function
typedef void (*fp)();
define your functions
void func1()
{}
.
.
.
void func10()
{}
declare array of function pointers like below
fp function_pointers[10]; //declares the array
Initialize the function pointers like below
function_pointers[0] = func1()
.
.
function_pointers[9] = func10()
Call function using function pointers like below
for (int i=0;i<10;i++)
function_pointers[i]();
Use function pointers.
Simple example:
#include <stdio.h>
//pointer to a void function declaration
typedef void(*someFunc)();
void f1() {
printf("f1 function call\n");
}
void f2() {
printf("f2 function call\n");
}
void f3() {
printf("f3 function call\n");
}
//array of function pointers
const someFunc funcTable[] = {
f1,
f2,
f3
};
int main() {
uint number = 0;
printf("Enter 0, 1 or 2\n");
scanf("%u",&number);
if(number < 3) {
funcTable[number]();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With