Re:Gosh Darn Function Pointers
by femto113 on Monday January 15, 2018 @04:38PM
(#16153679)
I've always found a typedef of the function and doing the pointer in the variable declaration the clearest since it doesn't need funky parentheses or dereferences anywhere:
[ Parent
| on HN ]
I am a little lost. What effect does `typedef int func(int arg);` have on the code?
Re:Gosh Darn Function Pointers
by inopinatus on Monday January 15, 2018 @05:34PM
(#16154063)
It allows the later definition of func * f which is more readable and maintainable than int (* f)(int arg)
This pattern is common in well-structured applications, and is especially useful for clarifying external and internal APIs. e.g. from the Dovecot IMAP server:
typedef bool event_callback_t(struct event *event,
enum event_callback_type type,
struct failure_context *ctx,
const char *fmt, va_list args);
You can now define a function pointer or declare a parameter using event_callback_t. This is both concise and intention revealing.It says that `func` is a type whose values are all functions with the signature `int foo(into arg)`.
The way to read a typedef (in general) is when you strip off the word "typedef", instead of declaring a type, it declares a value of that type. This applies to all types, not just function types. For example, an array of 5 ints is declared as
int foo[5];
So the type of all 5-element arrays is defined by typedef int FiveLongIntArray[5];