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.
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.
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.
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)++; .
There are three ways to pass variables to a function – pass by value, pass by pointer and pass by reference.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With