See i have a program in c or c++.. this program has many functions like add(), mul(), div(), sub() etc....

now i want to call a function such that in main there should be only one call for that particular funtion that i have to be called... ie in runtime i have to call a particular function...

main()
{
function_call();
}

add()
{
fun body
}

mul()
{
fun body
}

div()
{
fun body
}

sub()
{
fun body
}

Like this i have 4 fun ok.. i have to call one funtion at runtime .. not at compile time... main should have 0nly one calling function name...

how to do it... please help me...

one way to do it is to create an array of function pointers with associated strings for the name of the function. For example, support you type in "add", you would search the array for that word and when found call the associated function, something like this:

struct functions
{
    std::string function_name;
    void *fn();
};

functions fns[] = {
  {"add", add},
  {"subtract", sub},
 // etc etc for each function
};

int main()
{
   std::string cmd;
   cout << "Enter command\n";
   cin >> cmd;
   // now search the array for the command and call the associated function
   // not shown here.
}

> See i have a program in c or c++
Better make your mind up as to which language you're using then.

Because saying you're using C/C++ is like walking down the middle of the road blindfolded. Sooner or later, you're going to wind up being road-kill.

FWIW, the solution in C looks nothing like the solution in C++.

> See i have a program in c or c++
Better make your mind up as to which language you're using then.

Because saying you're using C/C++ is like walking down the middle of the road blindfolded. Sooner or later, you're going to wind up being road-kill.

FWIW, the solution in C looks nothing like the solution in C++.

Ok sir, using C give me the solution ...

Afterwards in C++ give me the solution...

any way i want to achieve this in any of these languages C or C++.. .." LOGIC " is important for me ...... :-)

Perhaps function_call() can be passed a parameter, which is then used in a switch/case.

Perhaps some kind of class wrapper using operator overloading.

Perhaps taking AD's search and replacing it with std::map to do all the lookup for you.

This article has been dead for over six months. Start a new discussion instead.