Salam Hanna
Salam Hanna

Reputation: 99

passing an array of functions by reference C++

There are multiple functions in a file (let's say file1.h). These functions are similar by their definition and return value. The file itself, it is not allowed to change it. I wanna simplify them like this:

file1.h

int func1 (void)
{
    return 11;
}
int func2(void)
{
    return 12;
}
int func3(void)
{
    return 13;
}

In my source file, which I am allowed to change, I would like to create an array of functions then pass this array by reference to another function, the code here is also simplified:

source_file.cpp

static int func_main(const int idx, int* arr_of_func)
{
    int ret = 0;
    switch (idx)
    {
        case 1:
            ret = arr_of_func[0];
            break;
        case 2:
            ret = arr_of_func[1];
            break;
        case 3:
            ret = arr_of_func[0];
            break;
        default:
            ret = -1;
            break;
    }

    return ret;
}

int main()
{
    std::cout << "Hello World!\n";
    int x = 0;
    cin >> x;
    int (*arr[3])(void) = {func1, func2, func3};

    cout << func_main(x, *arr);
    system("pause");
}

By invoking the function func_main(x, *arr) I don't know how to pass the array (the second argument). I need your help please. Thanks.

Upvotes: 1

Views: 79

Answers (1)

alex_noname
alex_noname

Reputation: 32233

Correct func_main parameter int* arr_of_func to array of function pointers int (*arr_of_func[3])(). Arrays are passed by reference by default.

#include <string>
#include <functional>
#include <iostream>

int func1 (void)
{
    return 11;
}
int func2(void)
{
    return 12;
}
int func3(void)
{
    return 13;
}

static int func_main(const int idx, int (*arr_of_func[3])())
{
    int ret = 0;
    switch (idx)
    {
        case 1:
            ret = arr_of_func[0]();
            break;
        case 2:
            ret = arr_of_func[1]();
            break;
        case 3:
            ret = arr_of_func[2]();
            break;
        default:
            ret = -1;
            break;
    }

    return ret;
}

int main()
{
    std::cout << "Hello World!\n";
    int x = 0;
    std::cin >> x;
    int (*arr[3])(void) = {func1, func2, func3};

    std::cout << func_main(x, arr);
    system("pause");
}

Upvotes: 2

Related Questions