Function pointers

suggest change

Pointers can also be used to point at functions.

Let’s take a basic function:

int my_function(int a, int b){    return 2 * a + 3 * b;}

Now, let’s define a pointer of that function’s type:

int (*my_pointer)(int, int);

To create one, just use this template:

return_type_of_func (*my_func_pointer)(type_arg1, type_arg2, ...)

We then must assign this pointer to the function:

my_pointer = &my_function;

This pointer can now be used to call the function:

/* Calling the pointed function */int result = (*my_pointer)(4, 2);.../* Using the function pointer as an argument to another function */void another_function(int (*another_pointer)(int, int)){    int a = 4;    int b = 2;    int result = (*another_pointer)(a, b);    printf("%d\n", result);}

Although this syntax seems more natural and coherent with basic types, attributing and dereferencing function pointers don’t require the usage of & and \* operators. So the following snippet is equally valid:

/* Attribution without the & operator */my_pointer = my_function;/* Dereferencing without the * operator */int result = my_pointer(4, 2);

To increase the readability of function pointers, typedefs may be used.

typedef void (*Callback)(int a);void some_function(Callback callback){    int a = 4;    callback(a);}

Another readability trick is that the C standard allows one to simplify a function pointer in arguments like above (but not in variable declaration) to something that looks like a function prototype; thus the following can be equivalently used for function definitions and declarations:

void some_function(void callback(int))
{
    int a = 4;
    callback(a);
}

See also

http://stackoverflow.com/documentation/c/250/function-pointers#t=201701141235586038319

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents