Concept
How can function pointers point to and call different functions?
ComputerScienceOne / Generalized Rounding
"double x = ptrToSqrt(2.0);\n\nSome more examples:\n\n1 //this pointer can point any function that takes\n\n2 //three arguments: an int, double, and a char\n\n3 //and returns an int value\n\n4 int (*ptrToFunc)(int, double, char)= NULL;\n\n5\n\n6 double x;\n\n7 double (*ptr)(double) = NULL;\n\n8 //we can make it point to sqrt:\n\n9 ptr = sqrt;\n\n10 x = ptr(2.0); //x contains 1.4142...\n\n11 //or we can make it point to fabs\n\n12 ptr = fabs;\n\n13 x = ptr(-10.5); //x contains 10.5\n\nYou generally want to create and use function pointers when passing and returning functions as arguments to other functions as callbacks. We discuss this in further detail in Chapter 25."
Related Ideas
- What is a function pointer and how is it declared?ComputerScienceOne · Function Pointers
- How do callbacks make C functions more generic?ComputerScienceOne · Function Pointers
- How can pointer arithmetic and comparators implement a generic getMax()?ComputerScienceOne · Function Pointers
- How are generic getMax() functions used with integers and structures?ComputerScienceOne · Function Pointers
- How can functions be assigned to variables and invoked as callbacks?ComputerScienceOne · Function Pointers
- How can qsort() sort an array of strings using pointers?ComputerScienceOne · Sorting Pointers to Elements
- How do you invoke functions that accept pointer parameters?ComputerScienceOne · Passing By Reference
- How do you call a function in C?ComputerScienceOne · Calling Functions