Home > Back-end >  C : array of pointers to functions
C : array of pointers to functions

Time:10-22

Say we have 2 functions

foo() { cout << "Hello"; }
foo2() { cout << " wolrd!"; }

how can i create an array of pointers (say a, b), with a pointing to foo() and b to foo2() ? my goal is to store these pointers in an array A, then loop over A to execute these functions.

CodePudding user response:

You can use typed function pointers as follows:

using FunPtrType = void(*)();

FunPtrType arr[]{&foo,  &foo2};
// or
std::array<FunPtrType, 2> arr2{&foo,  &foo2};

// ... do something with the array of free function pointers
// example
for(auto fun: arr2)
    fun();

CodePudding user response:

There is a simple implementation:

#include <iostream>
#include <vector>
using namespace std;
// Defining test functions
void a(){cout<<"Function A"<<endl;}
void b(){cout<<"Function B"<<endl;}

int main()
{
    /*Declaring a vector of functions 
      Which return void and takes no arguments.
    */
    vector<void(*)()> fonc;
    //Adding my functions in my vector
    fonc.push_back(a);
    fonc.push_back(b);
    //Calling with a loop.
    for(int i=0; i<2; i  ){
        fonc[i]();
    }
    return 0;
}


CodePudding user response:

There's no need for typedefs these days, just use auto.

#include <iostream>
void foo1() { std::cout << "Hello"; }
void foo2() { std::cout << " world!"; }
auto foos = { &foo1, &foo2 };
int main() { for (auto foo : foos) foo(); }

CodePudding user response:

There are two equivalent ways to do what you want:

Method 1


#include <iostream>
void foo() 
{ 
    std::cout << "Hello";
}
void foo2() 
{ 
    std::cout << " wolrd!"; 
    
}


int main()
{
   
    void (*a)() = foo;// a is a pointer to a function that takes no parameter and also does not return anything
    
    void (*b)() = foo2;// b is a pointer to a function that takes no parameter and also does not return anything
    
    
    //create array(of size 2) that can hold pointers to functions that does not return anything and also does not take any parameter
    void (*arr[2])() = { a, b};
    
    arr[0](); // calls foo 
    
    arr[1](); //calls foo1
    
    return 0;
}

Method 1 can be executed here.

Method 2


#include <iostream>
void foo() 
{ 
    std::cout << "Hello";
}
void foo2() 
{ 
    std::cout << " wolrd!"; 
    
}


int main()
{
   
    //create array(of size 2) that can hold pointers to functions that does not return anything
    void (*arr[2])() = { foo, foo2};
    
    arr[0](); // calls foo 
    
    arr[1](); //calls foo1
    
    return 0;
}

Method 2 can be executed here.

  • Related