Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an asterisk optional in a function pointer?

Tags:

c

function

The code I am using has this statement:

typedef void  ( udp_data_notify )(OS_FIFO * pfifo, WORD port); 

This looks like a declaration of a function pointer for udp_data_notify, however there is no *. Can it still be a function pointer without an asterisk?

Here is a statement that uses udp_data_notify:

void RegisterUDPFifoWithNotify( WORD dp, OS_FIFO *pnewfifo , udp_data_notify * nudp)

Any help as to what is happening would be appreciated!

like image 239
Sam Mallicoat Avatar asked Jul 28 '13 23:07

Sam Mallicoat


2 Answers

A typedef such as:

typedef void name(int);

(the parenthesis around name are redundant) will define name as the type of a function, not a function pointer. That would be:

typedef void (*pname)(int);

You are probably wondering what they are good for. Well, function types are not very useful, other than for declaring pointers:

name *pointer_to_function;

And that can be made arguably more readable with the other typedef:

pname pointer_to_function;

That's because you cannot define a variable of type function. If you try, you will simply write the prototype of a function, but in a quite obfuscated syntax:

name foo;   //declaration (prototype), not variable
void foo(int x) //definition
{
}

But note that you cannot use the typedef to define the function:

name foo {} //syntax error!
like image 104
rodrigo Avatar answered Sep 21 '22 01:09

rodrigo


As already said, the typedef declares an alias for function type. When you want to use it to declare a function pointer, an asterisk is required (udp_data_notify* x). A declaration without the asterisk (udp_data_notify x) would be a function declaration, except in one special case. When used in a parameter a function type is automatically turned into the corresponding function pointer type:

typedef void F(void);
void foo(F a, F* b) // special case; a and b are both function pointers
{
    F c; // function declaration
    F* d; // function pointer
}
like image 29
Timo Avatar answered Sep 20 '22 01:09

Timo