If you wanted to be able to assign a pointer to a function and then later change what that pointer points to then use auto fp = func
. If not then use a reference auto& rp = func
since you cannot reassign it:
#include <iostream>
using namespace std;
int funcA(int i, int j) {
return i+j;
}
int funcB(int i, int j) {
return i*j;
}
int main(int argc, char *argv[]) {
auto fp = funcA;
auto& rp = funcA;
cout << fp(1, 2) << endl; // 3 (1 + 2)
cout << rp(1, 2) << endl; // 3 (1 + 2)
fp = funcB;
//rp = funcB; // error: assignment of read-only reference 'rp'
cout << fp(1, 2) << endl; // 2 (1 * 2)
return 0;
}
I was trying to come up with a more practical example of why anyone would ever do this, below is some code that uses an array of pointers to call a function based on user input (any element of arr
could also be changed during run time to point to another function):
#include <iostream>
using namespace std;
void funcA(int i, int j) {
std::cout << "0: " << i << ", " << j << endl;
}
void funcB(int i, int j) {
std::cout << "1: " << i << ", " << j << endl;
}
void funcC(int i, int j) {
std::cout << "2: " << i << ", " << j << endl;
}
int main(int argc, char *argv[]) {
if (argc < 2) {
cout << "Usage: ./a.out <val>" << endl;
exit(0);
}
int index = atoi(argv[1]);
if (index < 0 || index > 2) {
cout << "Out of bounds" << endl;
exit(0);
}
void(* arr[])(int, int) = { funcA, funcB, funcC };
arr[index](1, 2);
return 0;
}