5

I saw some BSD code using the following construct:

typedef int driver_filter_t(void*);

What does that mean, exactly? I don't think it's a function pointer because otherwise it would be something like typedef int (*driver_filter_t)(void*), right?

Martin
  • 940
  • 6
  • 26

2 Answers2

9
typedef int driver_filter_t(void*);

This is a definition of a function type. It makes driver_filter_t an alias for the type that can be described as "function returning int with an argument of type pointer to void".

As for all typedefs, it creates an alias for an existing type, not a new type.

driver_filter_t is not a pointer type. You can't declare something of type driver_filter_t (the grammar doesn't allow declaring a function using a typedef name). You can declare an object that's a function pointer as, for example:

driver_filter_t *func_ptr;

Because you can't use a function type name directly without adding a * to denote a pointer type, it's probably more common to define typedefs for function pointer types, such as:

typedef int (*driver_filter_pointer)(void*);

But typedefs for function types are pefectly legal, and personally I find them clearer.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
  • Great answer. I wish K&R had given more attention to this kind of things in their book instead of rushing through the language. In practical terms, what would be the difference between using a typedef for a function type and a typedef for a function pointer, since you'll be dealing with pointers anyway? Is there anything you can do with the former that you can't do with the latter? Thanks a lot! – Martin Jun 06 '14 at 12:37
1

typedef int driver_filter_t(void*); is a typedef for a function type. In C you can use it for function pointers like driver_filter_t* fn_ptr.

In C++ you can also use that typedef to declare member functions (but not to implement them):

struct Some {
    driver_filter_t foo; // int foo(void*);
    driver_filter_t bar; // int bar(void*);
};
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • 2
    Hi Maxim. Just my opinion, but the OP tagged this question specifically for C. It's interesting that you can declare member functions for C++ as you show. However, I think it may cause confusion for someone who is becoming familiar with the C language - particularly since you cannot use that syntax in C. – embedded_guy Jun 05 '14 at 16:49
  • @embedded_guy Confused people get clarified the hell out of them here. – Maxim Egorushkin Jun 05 '14 at 17:13
  • 1
    You can also use the typedef in place of a function declaration in C, e.g. `driver_filter_t filterA, filterB, filterC;` in place of `int filterA(void*); int filterB(void*); ...` – tab Jun 05 '14 at 20:43