Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing function pointers as arguments [duplicate]

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.

like image 627
CuriousSid Avatar asked Mar 26 '13 17:03

CuriousSid


People also ask

Are pointers copied when passed as an argument?

Yes to both. Pointers are passed by value as anything else. That means the contents of the pointer variable (the address of the object pointed to) is copied.

Can we pass pointer as an argument to function?

Pass-by-pointer means to pass a pointer argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the variable to which the pointer argument points. When you use pass-by-pointer, a copy of the pointer is passed to the function.

How can we pass a pointer as an argument to a function explain with example?

Example 2: Passing Pointers to Functions Here, the value stored at p , *p , is 10 initially. We then passed the pointer p to the addOne() function. The ptr pointer gets this address in the addOne() function. Inside the function, we increased the value stored at ptr by 1 using (*ptr)++; .

How many ways can you pass a pointer to a function call?

There are three ways to pass variables to a function – pass by value, pass by pointer and pass by reference.


2 Answers

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.

like image 72
Joni Avatar answered Sep 28 '22 00:09

Joni


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

like image 44
cipher Avatar answered Sep 27 '22 22:09

cipher