I was wondering about the specific reason for which it is possible to use multiple times the dereferencing operator *
when we want to assign a function to a function pointer.
As an example, the following code perfectly compiles and runs:
#include <iostream>
void f() { std::cout << "Hello World!" << std::endl; }
int main() {
void(*f_ptr)(void) = ***************************************f;
f_ptr();
return 0;
}
Dereferencing (in way you think) a function's pointer means: accessing a CODE memory as it would be a DATA memory. Function pointer isn't suppose to be dereferenced in that way. Instead, it is called. I would use a name "dereference" side by side with "call". It's OK.
The dereference operator is also known as an indirection operator, which is represented by (*). When indirection operator (*) is used with the pointer variable, then it is known as dereferencing a pointer. When we dereference a pointer, then the value of the variable pointed by this pointer will be returned.
Dereferencing is used to access or manipulate data contained in memory location pointed to by a pointer. * (asterisk) is used with pointer variable when dereferencing the pointer variable, it refers to variable being pointed, so this is called dereferencing of pointers. Here, address in p is basically address of a variable.
Two similar experiments you can try: What happens if you dereference a function pointer in an lvalue context—the left-hand side of an assignment. An array value is also converted to a pointer in an lvalue context, but it is converted to a pointer to the element type, not to a pointer to the array.
Functions and references to functions decay to a function pointer whenever necessary. There is no dereference operator defined for functions but there is one for function pointer: the function or reference to function happily decays to a pointer just to become derefernced again.
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