Home >Backend Development >C++ >What Happens When You Dereference a Function Pointer in C?
Function Pointer Dereferencing: Unraveling the Mystery
Contrary to the assumption that dereferencing a function pointer accomplishes nothing, it initiates a unique behavior in C. Function pointers are not dereferenced in the conventional sense of accessing data memory as code memory.
Instead, dereferencing a function pointer in an rvalue context (such as in the example code provided) triggers its immediate conversion to a pointer to the original function. Surprisingly, subsequent dereferencing of this pointer retrieves the same function value, which is then promptly converted back into a pointer. This cycle can be repeated indefinitely.
This behavior becomes especially evident when examining function pointers in an lvalue context (e.g., the left-hand side of an assignment). Unlike arrays, which convert to element pointers, function values convert to pointers to their own type. Thus, dereferencing a function pointer in an lvalue context assigns a new function to the pointer.
The rationale behind the implicit conversion of function values to pointers is purely practical. For programmers using function pointers, it eliminates the necessity of writing &'s extensively. Conversely, function pointers in call position automatically revert to function values, obviating the use of * to invoke them.
The above is the detailed content of What Happens When You Dereference a Function Pointer in C?. For more information, please follow other related articles on the PHP Chinese website!