Bifalgorithm post · Computer science one · Function Pointers

How are function pointers declared and used in C?

How are function pointers declared and used in C? (Computer science one · Function Pointers) — "18.2.2. Function Pointers\n\nFunctions are just pieces of code…

Ideas in this flowchart

  • Function pointers
  • Functions are pieces of code stored somewhere in memory, like variables.
  • A function pointer is a variable that points to a function.
  • Declaring a function pointer requires its return type and parameter list.
  • The syntax can describe a pointer to the sqrt() function, which takes one double and returns a double.
  • double (*ptrToSqrt)(double) = NULL;
  • The pointer is named ptrToSqrt and is initialized to NULL.
  • ptrToSqrt = sqrt;
  • A function's identifier acts as a pointer to that function.
  • A function can be invoked through its pointer like any other function call.
Feed/

How are function pointers declared and used in C?

No cover

Channel

Computer science one

1 page

"18.2.2. Function Pointers\n\nFunctions are just pieces of code that reside somewhere in memory just as variables do. Since we can create pointers that point to variables, it makes sense to be able to create variables that point to functions too! These are referred to as function pointers. The syntax for declaring function pointers is similar to variable pointers. However, since a function’s signature involves a return type and parameter list, these need to be specified. For example, suppose we wanted to create a function pointer that could point to the math library’s sqrt() function which takes a single double parameter and returns a double value.\n\ndouble (*ptrToSqrt)(double) = NULL;\n\nThe above line creates a function pointer that can point to any function that takes a single double parameter and returns a double value. As is good practice, we’ve initialized it to point to NULL. The function pointer itself is named ptrToSqrt. To make it point to the sqrt() function we can use the following syntax.\n\nptrToSqrt = sqrt;\n\nThis is because a function’s identifier acts as a pointer as well! Once we have a pointer to a function, we can invoke the function via its pointer as we would any other function call."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.