Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it possible to use the dereferencing operator multiple times when assigning a function to a function pointer? [duplicate]

Tags:

c++

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;
} 
like image 374
FdeF Avatar asked Dec 12 '16 09:12

FdeF


People also ask

What does it mean to dereference a function pointer?

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.

What is dereference operator in C++?

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.

What is the use of dereferencing in C++?

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.

What happens if you dereference a function pointer in an lvalue context?

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.


1 Answers

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.

like image 124
Dietmar Kühl Avatar answered Nov 09 '22 19:11

Dietmar Kühl