nick_name
nick_name

Reputation: 1373

C - Strange Prototype Argument

What's going on in this function prototype? Obviously the void parameter with some sort of typecasting is confusing...

int *my_func(my_struct *m, void (*m_op)(my_struct *v, void arg));

Upvotes: 1

Views: 134

Answers (4)

Agnius Vasiliauskas
Agnius Vasiliauskas

Reputation: 11267

My suggestion - always try to split declarations into smaller ones - in that case code will be more readable. In this case you could re-write code as:

typedef struct {} my_struct;

typedef void (* m_op_function)(my_struct * v, void * arg);

int * my_func(my_struct * m, m_op_function f);

And as everybody said- it's almost 99,99% typo here regarding second parameter to m_op_function- it is possible void* - so that you can pass any pointer to it - be it (char*), (int*), (my_struct*), or anything else. Simply just cast pointer.

Upvotes: 0

Alexey Frunze
Alexey Frunze

Reputation: 62048

This little article explains how to parse C declarations in a spiral-like motion. Constructing is done in the reverse.

Upvotes: 0

Jonathan Callen
Jonathan Callen

Reputation: 11571

This prototype declares a function, my_func that returns int *. It takes two arguments, the first being of type my_struct * and the second of the strange type void (*)(my_struct *, void). This means that the second argument is a pointer to a function that returns void and takes 2 arguments itself, a pointer to my_struct and void (I assume that was a typo and it takes a void *).

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 753725

The second argument to the function my_func is a pointer to a function that returns no value (void), but which takes two arguments, a my_struct pointer and ... and (an invalid) void. The latter should probably be void *arg; you cannot have a variable or argument of type void. As it stands, the code should not compile.

Upvotes: 10

Related Questions