How to Use Function Pointers in C

A function pointer is, in essence, just a pointer to a function. In languages such as C++, each function and variable in a computer program exists as a memory address, and a variable can contain the value of that address. That variable can be passed to a callback, which can then call the function that the variable points to. It can also be used in an event manager, or for late binding of a member function. Due to their complicated syntax, function pointers are often avoided by programmers, but can be used to easily accomplish many powerful tasks.

Instructions

Things Youll Need:

  • C++ compiler
  1. Step 1

    Write a C++ program. This is the program in which you will use a function pointer.

  2. Step 2

    Define a function pointer. You can do this one of several ways. Declare a function, such as:

    void doSomething(int data);

    and later declare a pointer to it. Or, you can declare a function as a pointer:

    void (*doSomething)(int);

    Lastly, you can declare a typedef, then create a variable of that type.

    typedef void (*voidTakingInt)(int);

    You can now use "voidTakingInt" as a type:

    void doSomething(int data);
    voidTakingInt fun_ptr = &doSomething;

  3. Step 3

    Declare something that uses the function pointer. This will often be something that uses the function pointer as a callback function, so that when a specific event occurs, the function runs your function. One example is a file-loading function that takes a callback function to indicate progress.

  4. Step 4

    Call the function from the pointer to it. This would be done from within the function you wrote that accepts a function pointer as a parameter:

    void doSomething(int data) {
    }

    void callAnotherFunction(void (*otherFunction)(int)) {

    (*otherFunction)(3);

    }

    int main(int argc, char* argv[]) {

    callAnotherFunction(&doSomething);
    return 0;

Related Posts by Categories

0 comments:

Post a Comment