Bifalgorithm post · Computer science one · Generalized Rounding

How can function pointers point to and call different functions?

How can function pointers point to and call different functions? (Computer science one · Generalized Rounding) — "double x = ptrToSqrt(2.0);\n\nSome more examp…

Ideas in this flowchart

  • C function pointers allow functions to be referenced and called through pointer variables.
  • A function pointer’s type specifies the return type and parameter types of the referenced function.
  • int (*ptrToFunc)(int, double, char) = NULL;
  • The pointer can reference any function that takes an int, double, and char and returns an int.
  • A pointer to a function taking one double argument can be declared as double (*ptr)(double) = NULL;
  • Assigning ptr = sqrt allows x = ptr(2.0), producing approximately 1.4142.
  • Assigning ptr = fabs allows x = ptr(-10.5), producing 10.5.
  • Function pointers are generally used to pass and return functions as arguments to other functions, such as callbacks.
  • The callback use of function pointers is discussed further in Chapter 25.
  • A function pointer can also be used in an expression such as double x = ptrToSqrt(2.0);
Feed/

How can function pointers point to and call different functions?

No cover

Channel

Computer science one

1 page

"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."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.