Can you write an example of how function pointers work in C?
- User
Can you write an example of how function pointers work in C?
Assistant
Sure, here's an example of function pointers in C:
#include <stdio.h> // Function declaration void (*func_ptr)(); int main() { // Function pointer initialization func_ptr = addNumbers; // Call function via pointer func_ptr(); return 0; } // Function definition int addNumbers() { return 5 + 3; }In this example, we declare a function pointer called
func_ptrthat points to a function that returns an integer. In themainfunction, we initializefunc_ptrto point to theaddNumbersfunction. Then, we call the function via the pointer by simply invokingfunc_ptr(). The output of this program is the sum of 5 and 3, which is 8.Function pointers can be used to pass functions as arguments to other functions or as return values from functions. They can also be used to implement polymorphism and abstract data types in C.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.