Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointers to functions

I have two basic Cpp tasks, but still I have problems with them. First is to write functions mul1,div1,sub1,sum1, taking ints as arguments and returning ints. Then I need to create pointers ptrFun1 and ptrFun2 to functions mul1 and sum1, and print results of using them. Problem starts with defining those pointers. I thought I was doing it right, but devcpp gives me errors in compilation.

#include <iostream>
using namespace std;

int mul1(int a,int b)
{
    return a * b;
}

int div1(int a,int b)
{
    return a / b;    
}

int sum1(int a,int b)
{
    return a + b;   
}

int sub1(int a,int b)
{
    return a - b;    
}


int main()
{
    int a=1;
    int b=5;

    cout << mul1(a,b) << endl;
    cout << div1(a,b) << endl;
    cout << sum1(a,b) << endl;
    cout << sub1(a,b) << endl;

    int *funPtr1(int, int);
    int *funPtr2(int, int);

    funPtr1 = sum1;
    funPtr2 = mul1;

    cout << funPtr1(a,b) << endl;
    cout << funPtr2(a,b) << endl;

    system("PAUSE");
    return 0;
}
38 assignment of function `int* funPtr1(int, int)'
38 cannot convert `int ()(int, int)' to `int*()(int, int)' in assignment

Task 2 is to create array of pointers to those functions named tabFunPtr. How to do that ?

like image 946
DevAno1 Avatar asked Dec 05 '22 02:12

DevAno1


2 Answers

Instead of int *funPtr1(int, int) you need int (*funPtr1)(int, int) to declare a function pointer. Otherwise you are just declaring a function which returns a pointer to an int.

For an array of function pointers it's probably clearest to make a typedef for the function pointer type and then declare the array using that typedef.

E.g.

funPtr_type array_of_fn_ptrs[];
like image 179
CB Bailey Avatar answered Dec 26 '22 17:12

CB Bailey


This int *funPtr1(int, int); declares a function.

This int (*funPtr1)(int, int);defines a function pointer.

This typedef int (*funPtr1)(int, int); defines a function pointer type.

If you think that's confusing, try to define a pointer to a function which returns an array of pointers to member functions... C's declaration syntax is a nightmare.

like image 31
sbi Avatar answered Dec 26 '22 17:12

sbi