2

In C one can define a function pointer, but is there a "type-name" for what's the pointer points to?

To elaborate, instead of void (*fubar)(void) could one have a type definition so that one could declare fubar as Frob* fubar?

skyking
  • 13,817
  • 1
  • 35
  • 57

3 Answers3

6

There is no standard type name for function pointers, like there is for int. Furthermore, there is no keyword to namespace a tag for them, like there is for struct. Instead, you are expected to use typedef if you want to refer to a function prototype, or a pointer to a function, by name.

Consider the following typedef:

typedef void Frob (void);

Without the typedef keyword, the declaration would be for a prototype of a function named Frob. With typedef, the name Frob is now a type alias for functions that match that prototype. So, it can be used like this:

Frob foo;
Frob *fubar = foo;
void foo (void) { puts(__func__); }
int main (void) { fubar(); }

In general, typedef works this way, where it can turn a variable declaration (sans initializer) into a type alias.

jxh
  • 69,070
  • 8
  • 110
  • 193
1
typedef void (*fubar_p)(void);

or

void typedef (*fubar_p)(void);

or

typedef void (fubar)(void);

or

void typedef (fubar)(void);

then you can do

fubar_p fun_p;

or

fubar *fun;

In both cases , fun and fun_p have the same meaning, pointer to function taking no parameter and returning nothing.

alinsoar
  • 15,386
  • 4
  • 57
  • 74
  • 1
    Is the `void typedef (*fubar)(void)` really correct? It looks identical `void typedef (*fubar_p)(void)` except the name. – skyking May 16 '19 at 07:39
0

Just typedef it.

typedef void(*Frob)(void);

void f(void)
{
    // your code goes here
}

int main()
{
    Frob fubar = f;
    fubar();
    return 0;
}
selbie
  • 100,020
  • 15
  • 103
  • 173