Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding C typedef

Tags:

c++

c

types

tcl

I am trying to understand this code which is from Tcl documentation

typedef int Tcl_DriverOutputProc(
        ClientData instanceData,
        const char *buf,
        int toWrite,
        int *errorCodePtr);

As I know the purpose of typedef is to assign alternative names to existing types, so why is needed to typedef int to function? How this can be used?

like image 612
Ashot Avatar asked Apr 17 '13 10:04

Ashot


1 Answers

I know the purpose of typedef is to assign alternative names to existing types

Exactly. Functions have types, and this assigns the name Tcl_DriverOutputProc to this function type. The function type itself is written like a function with the name missing:

int(ClientData, const char *, int, int *)

and, as with a function declaration, you can include names for the parameters, or leave them out, as you choose.

How this can be used?

You can use pointers to functions in order to specify behaviour at run-time; for example:

typedef void function();
void hello()   {printf("Hello\n");}
void goodbye() {printf("Goodbye\n");}

int main() {
    function * pf = hello;
    pf(); // prints "Hello"
    pf = goodbye;
    pg(); // prints "Goodbye"
}

In this case, it allows you to write a function to handle some aspect of TCL output, and tell TCL to use that function.

like image 68
Mike Seymour Avatar answered Oct 20 '22 14:10

Mike Seymour