Ad

How To Understand "(*****************p)();" In C

- 1 answer

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;
}
Ad

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.

Ad
source: stackoverflow.com
Ad