+ 1
Function pointer
can anybody provide me some sniptes of function pointer?
12 Answers
+ 3
int foo(int arg);
int bar(int arg);
int callfunc(int (*func) (int), arg){
return func(arg);
}
int (*x) (int);
x = foo;
callfunc(x, 3); //same as foo(3);
x = bar;
callfunc(x, 3); //same as bar(3);
+ 8
~ swim ~
Thanks for taking your time and made it for us as clear as possible. Personally, I don't know anything about C++ when it comes to fine details!. But most of the times I do my best to provide something useful. Thanks again. ;-]
+ 6
As I already mentioned, the context is totally different. Just to make sure that I inadvertently didn't something wrong, I put together the following code as a proof that the * sign is optional even in class interface where you place all method prototypes. I even test it on three different compiler (G++, MinGW, MSVC++) with separate .h and .cpp sources. Hopefully your doubt is vanished Baptiste E. Prunier .
https://code.sololearn.com/c9fSx9vhpr3H/?ref=app
+ 5
~ swim ~ Thanks for clearing the subject ! I did not knew it was possible to remove the '*' when declaring the type
I come from C and I never saw it that way. It might work in C too, I'll do some experimenting on it
+ 4
Azam
class A {
public:
void f1(int (*fx)(int n), int val) {
int dx = (*fx)(val);
// ...
}
};
class B {
public:
static int f(int n) {
return n * n + 2 * n + 1;
}
};
int main() {
A a;
int number = 5;
a.f1(B::f, number);
}
Btw, * sign in (*fx) is optional.
+ 4
Baptiste E. Prunier
The context is different.
In my case, since I merely pass around function's name as a pointer, there's no need to declare it in main or anywhere else.
+ 3
a function pointer is declared like that :
return_type (*variable_name)(list of parameters);
you can then assign it a function. Let's do an example :
#include <stdio.h>
int max(int a, int b){
return a > b ? a : b;
}
int main(){
int (*m)(int, int);
m = max;
// or
m = &max;
printf("%d\n",m(1,2));
return 0;
}
+ 1
You can't remove it in the prototype of f1 C++ Soldier (Babak)
0
actually I want pass a function as parameter to a 2nd function.
1st function will be called in 2nd function.
0
ok I'll try to solve my problem with this solution.
thanks a lotđ
0
just to add to what C++ Soldier (Babak) said, * is optional when you USE fx, and only when you use it, it is mandatory when you declare it
0
Type in a code to declare a function that takes and returns void pointers.
void * foo(void *);