views:

231

answers:

6

Hi all, I want to ask about pointer in C++

I have some simple code:

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

int runner(int x,int y, int (*functocall)(int, int)){
 return (*functocall)(x,y);
}

now, suppose I call those functions using this way :

cout<<runner(2,5,&add);

or maybe

cout<<runner(2,5,add);

is there any difference? because when I tried, the result is the same and with no error.

Thanks a lot

A: 

I believe the second call automatically resolves to the first call in the compiler...

John Weldon
so you mean, the second call is the right one?
BobAlmond
no, I mean that the compiler resolves either call to a function pointer, and it's really a matter of syntactic preference.
John Weldon
+10  A: 

Function will be implicitly casted to a pointer according to C++ Standard (4.3/1). There is no difference. However this conversion never applies to nonstatic member functions. For them you should explicitly write &.

Kirill V. Lyadvinsky
+3  A: 

There is no difference. For consistency with other ways of getting a pointer you can use &, but the name by itself would have no other meaning so it is assumed to mean "get the address".

It's very similar to array variable names acting as the address of the first element of the array.

Daniel Earwicker
A: 

it is because there is no such object (in terms of expressions) as function, there are only pointers to functions. When you want to pass function to your function the only thing you can actually pass is pointer, so compiler does this cast for you

Andrey
There are objects called functions (in terms of expressions): `add` is such an object, its type is `int (int, int)`. They do implicitly decay to pointers to themselves in many contexts though.
avakar
please show example where function and pointer to function as expression term really differ
Andrey
Yes, functions aren't objects, but they are functions (surprise xD). For example `void f() { } void (` works because f is an expression of function type and you bind the reference to it, while `void (
Johannes Schaub - litb
+3  A: 

No, in this particular case there is no difference. Either one gives you the address of the function.

Note, however, that in C++, getting a pointer to a member function requires that you use the '&' operator.

Jerry Coffin
+1  A: 

Notice that you can have references to functions

int runner(int x,int y, int (&functocall)(int, int)){
 return functocall(x,y);
}

Now calling it with &add won't work anymore because you try to bind a function reference to a pointer instead of to a function. Sometimes this shines through when using templates

template<typename T>
int runner(int x,int y, T &functocall, T otherfunc){
 return functocall(x,y) + otherfunc(y, x);
}

Now calling it with runner(10, 20, add, add) will fail because T is tried to be deduced to both a function pointer and a function type (no decay to a pointer is done when passing to a reference parameter!).

Johannes Schaub - litb