how to properly use a function pointer to a particular function
#include <iostream>
using namespace std;
int function(int a,int b)
{
return a + b;
}
bool function2(int a,int b)
{
return a < b;
}
void function3(int c, int(*cmp)(int a,int b) )
{
bool (*compare)(int,int) = &function2;
if( (*compare)(c,(*cmp)(a,b)))
{
cout << " this number is way bigger then the two " <<endl;
}else{
cout << " this number is lower " <<endl;
}
}
int main(int argc,char *argv[])
{
int (*foo)(int,int) = &function;
int a = 5, b = 10;
int sum = (*foo)(a,b);
cout << " the sum of two values: " << sum <<endl;
bool (*foo2)(int,int) = &function2;
if((*foo2)(a,b))
{
cout << " this is the power of c " <<endl;
}else {
cout << " this is not the power of c " <<endl;
}
system("pause");
return EXIT_SUCCESS;
}
Re: how to properly use a function pointer to a particular function
Is there a question implied here, or are you just presenting this as an example?
Re: how to properly use a function pointer to a particular function
Re: how to properly use a function pointer to a particular function
When you post code, please format and indent it properly first and use code tags (Go Advanced, select code and click '#') so that the code is readable. Also, it would be useful if you actually asked a specific question!
As you haven't asked a specific question, I'm assuming you are referring to the compiler error regarding undeclared identifiers in the line
Code:
if ((compare)(c, (*cmp)(a, b))) {
This is because a and b haven't been declared!
Looking at the function definiton, you have
Code:
void function3(int c, int(*cmp)(int a,int b) )
This function takes 2 parameters. The first is an int, the second is a function that takes as arguments 2 ints and returns an int. The names of these arguments is ignored here by the compiler (you don't even need to provide them - the same way as you don't need to provide argument names in function declarations). If you want to pass two ints to function3 as well then the function definition would be
Code:
void function3(int c, int(*cmp)(int, int), int a, int b)
When dealing with function pointers, I like to use typedefs to define a function type.
Code:
typedef int (*IFUNCII)(int, int);
Which defines a type IFUNCII as a function pointer for functions that take 2 int parameters and return an int. Using this, the function3 definition would be
Code:
void function3(int c, IFUNCII cmp, int a, int b)
An example of using it is
Code:
function3(12, function, 5, 10);
I hope this helps.