Raindrop7
Raindrop7

Reputation: 3911

calling function depending on index of array array of functions' names

making random actions in a game makes it really look like real... so if a character has many capabilities like move, work, study... so in programming a function of those is called depending on some conditions. what we want is a more random and real-looking like action where no condition is there but depending on a random condition the character takes a random actions..

I thought to make actions (functions) in an array then declare a pointer to function and the program can randomly generate an index which on which the pointer to function will be assigned the corresponding function name from the array:

#include <iostream>

void Foo()   { std::cout << "Foo"    << std::endl; }
void Bar()   { std::cout << "Bar"    << std::endl; }
void FooBar(){ std::cout << "FooBar" << std::endl; }
void Baz()   { std::cout << "Baz"    << std::endl; }
void FooBaz(){ std::cout << "FooBaz" << std::endl; }


int main()
{

    void (*pFunc)();
    void* pvArray[5] = {(void*)Foo, (void*)Bar, (void*)FooBar, (void*)Baz, (void*)FooBaz};

    int choice;
    std::cout << "Which function: ";
    std::cin >> choice;
    std::cout << std::endl;

    // or random index: choice  = rand() % 5;

    pFunc = (void(*)())pvArray[choice];
    (*pFunc)();


    // or iteratley call them all:

    std::cout << "calling functions iteraely:" << std::endl;

    for(int i(0); i < 5; i++)
    {
        pFunc = (void(*)())pvArray[i];
        (*pFunc)();
    }

    std::cout << std::endl;
    return 0;
}

Upvotes: 0

Views: 681

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726539

There is absolutely no point in converting function pointers to void* and back. Define an array of function pointers, and use it as a normal array. The syntax for the declaration is described in this Q&A (it is for C, but the syntax remains the same in C++). The syntax for the call is a straightforward () application after the indexer [].

void (*pFunc[])() = {Foo, Bar, FooBar, Baz, FooBaz};
...
pFunc[choice]();

Demo.

Note: Although function pointers work in C++, a more flexible approach is to use std::function objects instead.

Upvotes: 5

Related Questions