views:

177

answers:

5

Everytime I look at a C function pointer, my eyes glaze over. I can't read them.

From here, here are 2 examples of function pointer TYPEDEFS:

typedef int (*AddFunc)(int,int);
typedef void (*FunctionFunc)();

Now I'm used to something like:

typedef vector<int> VectorOfInts ;

Which I read as

typedef vector<int> /* as */ VectorOfInts ;

But I can't read the above 2 typedefs. The bracketing and the asterisk placement, it's just not logical.

Why is the * beside the word AddFunc..?

+4  A: 

The actual type of the first one is

int (*)(int,int);

(that is, a pointer to a function that takes two parameters of type int and returns an int)

The * identifies it as a function pointer. AddFunc is the name of the typedef.

cdecl can help with identifying particularly complex type or variable declarations.

James McNellis
This is the weirdest thing ever! So if we have `float (*GetPtr1(const char opCode))(float, float)`, that is a function named `GetPtr1` who returns `float(*) (float,float)`. I find the second easier to read, why doesn't the syntax go `float(*)(float,float) GetPtr1(const char opCode);`? That would be [hella](http://www.youtube.com/watch?v=QtTj4cramPM) easier to read imo!
bobobobo
+5  A: 

When you're comprehending it, just ignore the typedef, the parentheses around the function name, and the asterisk in front of the name. Then you have int AddFunc(int,int);.

The point of the parentheses in (*functionName) is to specifically group the * with the name of the typedef. The * is necessary to indicate that this is a function pointer.

So any function that takes two ints as arguments and returns an int complies to the AddFunc "interface", if you will. Likewise, any function accepting no arguments are returning void can be used for a FunctionFunc.

Mark Rushakoff
Great explanation!
mingos
A: 

The asterisk indicates that it's a function POINTER :)

mingos
+3  A: 
sbi
+2  A: 

Function declarations look like this:

int AddFunc(int,int);
void FunctionFunc();

A typedef defining a function type looks the same, just with typedef in front:

typedef int AddFunc_t(int,int);
typedef void FunctionFunc_t();

To define a pointer to such a function type, there needs to be an additional * with additional parenthesis to specify where that * belongs to:

typedef int (*pAddFunc_t)(int,int);
typedef void (*pFunctionFunc_t)();

(The * is always right before the typename/variable that gets defined as a pointer.)

To read such a function pointer proceed in the opposite direction: leave out the (* ... ) around the type name and the typedef in front. The result then looks like a normal function declaration of the relevant type.

sth