Tech Support > Computers & Technology > Programming > Invoking a function through function pointer
Invoking a function through function pointer
Posted by Ravi kumar.N on April 25th, 2005


Respected Experts,
Iam Ravikumar.N, I have a query regarding
pointer to a function. I have a sample code, it is as follows


void func(int x, int y)
{
cout << x << "\n";
cout << y << "\n";
}


void main()
{
void (*fp)(int, int);

fp = func;
(*fp)(10, 20); //One way of invoking the function
fp(10, 20); //Another way of invoking the function
}

The above code reveals that the function "func" can be invoked in
two ways

i.e. 1)(*fp)(10, 20);
2) fp(10, 20);

I would like to know what is the difference between in these two
invocations.

With Regards
Ravi Kumar.N

Posted by Chris Dollin on April 25th, 2005


Ravi kumar.N wrote:

C++, then.

One has an unnecessary dereference operation written in it
(with brackets to enforce the correct grouping).

--
Chris "electric hedgehog" Dollin

Posted by Angad on April 25th, 2005


How does this work - (*fp)(10,20) ? Have you tried running it?
Shouldn't it give a run-time error?

Posted by Chris Dollin on April 25th, 2005


Angad wrote:

Yes.

No. I believe C++ follows (perhaps introduced) the C behaviour here.

--
Chris "electric hedgehog" Dollin

Posted by Andrey Tarasevich on April 25th, 2005


Ravi kumar.N wrote:
There's no difference. Both methods are legal. Both methods have the
same effect.

--
Best regards,
Andrey Tarasevich

Posted by Peter Nilsson on April 26th, 2005


Chris Dollin wrote:
It's a little known quirk that both C and C++ accept...

#include <stdio.h>

int main(void)
{
(***** /*...*/ *****puts)("Hello World!");
return 0;
}

Indirection on an expression with function type just produces the
same function designator.

--
Peter


Posted by Andrey Tarasevich on April 27th, 2005


Peter Nilsson wrote:
.... although the term "function designator" is C-specific. In C++ the
situation is a bit different and, for example, as a consequence of that,
the extra parentheses (with or without '*' inside) will disable
argument-dependent name lookup

namespace test {
struct s {};
void foo(s);
}

int main() {
test::s s;
foo(s); // OK
(foo)(s); // ERROR
(*foo)(s); // ERROR
}

--
Best regards,
Andrey Tarasevich


Similar Posts