C language basics: function pointers

        In the previous chapters we learned how to define and use a special type of variable - a pointer. In fact, pointers are also ordinary variables, but the values ​​they store represent the memory addresses of other variables. In this section we are going to learn another use of pointers to store the memory address of a function. E.g:

#include <stdio.h>
void myfunc(void)
{
	printf("my function.\n");
}
int main(int argc, char *argv[])
{
	void (*p)(void) = &myfunc;
	p();
	return 0;
}

        Here we define a pointer variable p, which points to the address of a function myfunc() we defined, which is &myfunc (same as ordinary variables, the operator for taking the variable address is &). Like this, when we define a pointer variable and make this pointer variable point to a function, we call this pointer a pointer to a function , or function pointer for short . Note that when defining a function pointer, parentheses (*p)(void) must be added around the pointer variable and * to indicate that this is a function pointer, and a pair of parentheses after it to indicate the parameters of the function.

        Then we can assign the address of a function to this pointer p. Once a pointer variable points to a function, the pointer variable can execute the function it points to. E.g:

p();

        The effect of executing this code is the same as the effect of executing myfunc();, and the running result is:

my functions.

        Next, let's define two pointers to functions with parameters and return values, which are used to calculate the sum of two numbers:

#include <stdio.h>
int add_int(int a, int b)
{
	return a + b;
}
float add_float(float a, float b)
{
	return a + b;
}
int main(int argc, char *argv[])
{
	int (*p0)(int, int) = &add_int;
	int res0 = p0(2, 3);
	float (*p1)(float, float) = &add_float;
	float res1 = p1(2.2, 3.3);
	printf("%d\n%f\n", res0, res1);
	return 0;
}

        We define two pointer variables, p0 points to the function add_int() and p1 points to the function add_float(). Finally, when we execute p0(2, 3);, it is equivalent to executing add_int(2,3); and when we execute p1(2.2, 3.3);, it is equivalent to executing add_float(2.2, 3.3);

        There are many benefits of using function pointers, for example, we can use function pointers to implement common data structures and common algorithms, etc. We will not introduce too much about the advanced usage of pointer functions in the series "C Language Basics" . If you are interested, you can refer to the "C Language Depths" series of tutorials.


Welcome to the public account: programming aliens

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325706196&siteId=291194637