Typedef'ing function pointers

Started by
2 comments, last by JohnBolton 19 years, 3 months ago
Quote: typedef void (*SIG_ TYP)(int) ; / / from <signal.h> typedef void (*SIG_ ARG_ TYP)(int) ; SIG_ TYP signal(int, SIG_ ARG_ TYP) ; An array of pointers to functions is often useful. For example, the menu system for my mousebased editor is implemented using arrays of pointers to functions to represent operations. The system cannot be described in detail here, but this is the general idea: typedef void (*PF)() ; PF edit_ ops[] = { / / edit operations &cut, &paste, ©, &search }; PF file_ ops[] = { / / file management &open, &append, &close, &write };
I have only read about the typedef operator but it's basic format is typedef type newname; So how in the world does "typedef void (*PF)() work? What is considered the type and how is PF the newname?
Advertisement
If you have a function of the type 'void func()' and you want to store the address of such a function in a variable, the type of the variable is 'void (*)()'. That is a pointer to a function without parameters and returning nothing.

When you introduce a new type using typedef, you place the name of the new type at the same position where you would normally place the name of a definition.

So 'typedef void(*PF)()' creates a new type which is a pointer to a function without parameters and returning nothing. You can then define a variable of that type

PF pf;

and assign a value, which is the address of a function

void func() {}
...
pf = func;
Also, you call func() (the function you assigned to pf) like this:

pf();

So you treat the function pointer just like a normal function

Drew Sikora
Executive Producer
GameDev.net

Quote:Original post by HughG
I have only read about the typedef operator but it's basic format is

typedef type newname;


Actually the syntax of a typedef is more like this:
    typedef declaration; 
The "declaration" is like a normal declaration except the name of the new type goes in the place where the variable normally goes.
John BoltonLocomotive Games (THQ)Current Project: Destroy All Humans (Wii). IN STORES NOW!

This topic is closed to new replies.

Advertisement