6

I was revisiting function pointers in C using the following simple code:

unsigned TestFn(unsigned arg)
{   
    return arg+7;
}

unsigned Caller(unsigned (*FuncPtr)(unsigned), unsigned arg)
{
    return (*FuncPtr)(arg);
}

I called it using

Caller(TestFn, 7)  //and
Caller(&TestFn, 7)

both gave the same output : 14. What's the explanation of this. I had been using the second way of calling earlier.

CuriousSid
  • 534
  • 3
  • 11
  • 25
  • 2
    I believe address is implicitely passed when you pass TestFn, so it is interpreted actually same like &TestFn. – Martinsos Mar 26 '13 at 17:03
  • 2
    I think this question answers it, even though it's C++ http://stackoverflow.com/questions/6893285/why-do-all-these-crazy-function-pointer-definitions-all-work-what-is-really-goi – Joe Mar 26 '13 at 17:03

2 Answers2

8

Functions work kind of like arrays here. Suppose you have:

char hello[5];

You can refer to the address of this variable directly as hello - the variable name "decays" into a pointer - or as &hello, which explicitly obtains the address.

Functions are the same: if you write TestFn it decays into a function pointer. But you can also use &TestFn. The latter form might be better because it is familiar to more people.

Joni
  • 108,737
  • 14
  • 143
  • 193
  • 1
    Thnx, as you said in case of arrays where hello and &hello are same, I experimented with the func ptrs and saw that they are a step ahead with: &ptr, ptr, *ptr, **ptr, ****..*ptr all being same. This appears a bit different from the arrays where dereferencing will give the element value. – CuriousSid Mar 26 '13 at 17:22
  • Yes, it is a little different: when you dereference a function pointer you obtain a function, represented by its address. But the address is also the value of the pointer. So if p is a function pointer, p == *p == **p == ... – Joni Mar 26 '13 at 18:24
2

Just like you pass the address of string without using the ampersand '&' sign, you don't need to use the ampersand sign to say you are passing a function pointer . You can search the book by K & R . It contains a good explaination

cipher
  • 2,414
  • 4
  • 30
  • 54