This is a C program of showing how to use a pointer to a function. The pointer to a function is available in ANSI-C as well as in C++ and works as described in this program. It is not regularly used by most C programmers, so it is defined here as a refresher.
A pointer to a function is a type of pointer that points to the address of a function in memory. A function pointer is declared using the syntax return_type (*function_pointer_name)(argument_list)
. To call a function through a function pointer, you need to dereference it using the (*function_pointer_name)
syntax and pass the required arguments in the parentheses.
Review our article titled Working with Pointers in C for a detailed discussion about pointers and how to use them in your C programs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | #include <stdio.h> void print_stuff(float data_to_ignore); void print_message(float list_this_data); void print_float(float data_to_print); void (*function_pointer)(float); main() { float pi = 3.14159; float two_pi = 2.0 * pi; print_stuff(pi); function_pointer = print_stuff; function_pointer(pi); function_pointer = print_message; function_pointer(two_pi); function_pointer(13.0); function_pointer = print_float; function_pointer(pi); print_float(pi); } void print_stuff(float data_to_ignore) { printf("This is the print stuff function.\n"); } void print_message(float list_this_data) { printf("The data to be listed is %f\n", list_this_data); } void print_float(float data_to_print) { printf("The data to be printed is %f\n", data_to_print); } |
Output of the C Program:
1 2 3 4 5 6 7 8 9 10 11 | This is the print stuff function. This is the print stuff function. The data to be listed is 6.283180 The data to be listed is 13.000000 The data to be printed is 3.141590 The data to be printed is 3.141590 |