1

Does anyone know how to understand the fourth line of the code shown below?

typedef short Signal;
typedef struct Event Event;
typedef struct Fsm Fsm;
typedef void (*State)(Fsm *, Event const *);
HeyMan
  • 163
  • 2
  • 11
  • Have a look at this post http://stackoverflow.com/questions/4295432/typedef-function-pointer – Mido Mar 25 '15 at 01:18

2 Answers2

2

It declares State as a typedef for void (*)(Fsm *, Event const *).

void (*)(Fsm *, Event const *) is a function pointer, pointing to a function that takes two arguments, Fsm * and Event const *, and returns void.

More information: How do function pointers in C work? and Typedef function pointer?

Community
  • 1
  • 1
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
1

Let's go through the typedefs one by one:

  • The first line creates an alias for the type short. Now you can write Signal xyz = 0; and it would be equivalent to writing short xyz = 0;
  • The second and third lines let you write declarations of variables of the two struct types without the struct keyword. In other words, you can now write Fsm myFsm; instead of writing struct Fsm myFsm;
  • The last line declares a type State that corresponds to a void function pointer taking a pointer to Fsm and a pointer to Event.

The syntax may be a little tricky because of all the parentheses and the name being typedef-ed not being at the end of the declaration. You can tell it's a type definition for a function pointer, because the name of the type is in parentheses, and is prefixed with an asterisk. The rest of the typedef looks very much like a function signature, so the result is easy to read.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523