Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call different functions on different int values in c

Tags:

c

function

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?

like image 556
Abhishek kumar Avatar asked Mar 06 '23 14:03

Abhishek kumar


2 Answers

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]();
like image 65
kiran Biradar Avatar answered Mar 08 '23 03:03

kiran Biradar


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]();
    }
}
like image 29
Denis Sablukov Avatar answered Mar 08 '23 03:03

Denis Sablukov