How To Understand "(*****************p)();" In C
I am a college student. I saw this way of writing in Expert C Programming. I don't understand why the function pointer can be called like this.
#include <stdio.h>
void fun(){}
int main(int argc, char const *argv[])
{
void (*p)() = fun;
(************************************************************************p)();
return 0;
}
Answer
This works because of how function designators and function pointers work.
When a function pointer is dereferenced, the result is a function designator. However, in most contexts a function designator is converted to a function pointer.
This behavior is spelled out in section 6.3.2.1p4 of the C standard:
A function designator is an expression that has function type. Except when it is the operand of the
sizeof
operator, the_Alignof
operator, or the unary&
operator, a function designator with type ‘‘function returning type’’ is converted to an expression that has type ‘‘pointer to function returning type’’.
What this means is that given function pointer p
, *p
is a function designator but is then converted back to a function pointer wherever it is used. This means a function pointer can be dereferenced (essentially) an unlimited number of times and yield the same result.
In addition, the function call operator ()
actually expects a function pointer as its argument. So if you were to execute fun()
, fun
would first be converted to a function pointer as per the above rule then the function call operator is applied to that function pointer.
Put those together, and that's what this code is demonstrating.
Related Questions
- → OctoberCMS Backend Loging Hash Error
- → "failed to open stream" error when executing "migrate:make"
- → OctoberCMS - How to make collapsible list default to active only on non-mobile
- → Create plugin that makes objects from model in back-end
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → How to install console for plugin development in October CMS
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → How to update data attribute on Ajax complete
- → October CMS - Conditionally Load a Different Page