简体   繁体   中英

Explicit dereference of function pointer In C

I have a piece of code which is an example of function pointer and have taken from Linux Kernel source .Below is the structure having callback function as its member

 struct parport_driver {
 const char *name;
 void (*attach) (struct parport *);
 struct parport_driver *next;
 };

Now member of these structure is called in C file like given below

 struct parport_driver *drv;

 drv->attach(port); /* calling function through implicit dereference */

Above function is called in implicit way but i want to know how it would be called explicit way.

What is difference between implicit and explicit way of dereferencing function pointer.

One more thing I would like to know structure member attach should be intialized before a call (drv->attach(port));

Somehing like

drv->attach=attach_driver_chain;

where attach_driver_chain is function but I could not find any such intialization in driver code.

The postfix () operator (function call) is defined to take a pointer to a function and call the function. So it is an explicit dereference of the pointer. There is no other way to call a function.

Although (*FunctionPointer)() looks like an explicit dereference, the type of the expression *FunctionPointer is a function. Per C 2011 6.3.2.1 4, an expression of function type is converted to a pointer to the function (except when the expression is the operand of sizeof , _Alignof , or & ). So, in (*FunctionPointer)() , *FunctionPointer is converted to be the same as FunctionPointer and nothing has been accomplished: The expression is the same as before, and the () operator acts on a function pointer, not a function.

There is no difference between calling a function with FunctionPointer() and calling it with (*FunctionPointer)() . You could even write (***************FunctionPointer)() with the same effect. Each of the * operators will be nullified by the automatic conversion.

Above function is called in implicit way but wanted to know how it would be called explicit way.

Like this:

(*(drv->attach))(port); // Not very pretty, huh?

What is difference between implicit and explicit way of dereferencing function pointer

There is no difference: since all you can do with a function pointer is call a function that it points to, compiler ignores explicit dereferences of function pointers.

This example may help also

struct product
{
    string name;
    int weight;
    double price;
};

product *p1 = new product();
(*p1).name = "orange"; // This is an explicit dereferencing
p1->name = "orange";   // This is also an explicit dereferencing

product *p2 = &p1;
p2.name = "apple"; // This is an implicit dereferencing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM