Search

7.8 — Function Pointers

In lesson 6.7 -- Introduction to pointers, you learned that a pointer is a variable that holds the address of another variable. Function pointers are similar, except that instead of pointing to variables, they point to functions!

Consider the following function:

Identifier foo is the function’s name. But what type is the function? Functions have their own l-value function type -- in this case, a function type that returns an integer and takes no parameters. Much like variables, functions live at an assigned address in memory.

When a function is called (via the () operator), execution jumps to the address of the function being called:

At some point in your programming career (if you haven’t already), you’ll probably make a simple mistake:

Instead of calling function foo() and printing the return value, we’ve unintentionally sent function foo directly to std::cout. What happens in this case?

On the author’s machine, this printed:

0x002717f0

…but it may print some other value (e.g. 1) on your machine, depending on how your compiler decides to convert the function pointer to another type for printing. If your machine doesn’t print the function’s address, you may be able to force it to do so by converting the function to a void pointer and printing that:

Just like it is possible to declare a non-constant pointer to a normal variable, it’s also possible to declare a non-constant pointer to a function. In the rest of this lesson, we’ll examine these function pointers and their uses. Function pointers are a fairly advanced topic, and the rest of this lesson can be safely skipped or skimmed by those only looking for C++ basics.

Pointers to functions

The syntax for creating a non-const function pointer is one of the ugliest things you will ever see in C++:

In the above snippet, fcnPtr is a pointer to a function that has no parameters and returns an integer. fcnPtr can point to any function that matches this type.

The parenthesis around *fcnPtr are necessary for precedence reasons, as int *fcnPtr() would be interpreted as a forward declaration for a function named fcnPtr that takes no parameters and returns a pointer to an integer.

To make a const function pointer, the const goes after the asterisk:

If you put the const before the int, then that would indicate the function being pointed to would return a const int.

Assigning a function to a function pointer

Function pointers can be initialized with a function (and non-const function pointers can be assigned a function):

One common mistake is to do this:

This would actually assign the return value from a call to function goo() to fcnPtr, which isn’t what we want. We want fcnPtr to be assigned the address of function goo, not the return value from function goo(). So no parenthesis are needed.

Note that the type (parameters and return type) of the function pointer must match the type of the function. Here are some examples of this:

Unlike fundamental types, C++ will implicitly convert a function into a function pointer if needed (so you don’t need to use the address-of operator (&) to get the function’s address). However, it will not implicitly convert function pointers to void pointers, or vice-versa.

Calling a function using a function pointer

The other primary thing you can do with a function pointer is use it to actually call the function. There are two ways to do this. The first is via explicit dereference:

The second way is via implicit dereference:

As you can see, the implicit dereference method looks just like a normal function call -- which is what you’d expect, since normal function names are pointers to functions anyway! However, some older compilers do not support the implicit dereference method, but all modern compilers should.

One interesting note: Default parameters won’t work for functions called through function pointers. Default parameters are resolved at compile-time (that is, if you don’t supply an argument for a defaulted parameter, the compiler substitutes one in for you when the code is compiled). However, function pointers are resolved at run-time. Consequently, default parameters can not be resolved when making a function call with a function pointer. You’ll explicitly have to pass in values for any defaulted parameters in this case.

Passing functions as arguments to other functions

One of the most useful things to do with function pointers is pass a function as an argument to another function. Functions used as arguments to another function are sometimes called callback functions.

Consider a case where you are writing a function to perform a task (such as sorting an array), but you want the user to be able to define how a particular part of that task will be performed (such as whether the array is sorted in ascending or descending order). Let’s take a closer look at this problem as applied specifically to sorting, as an example that can be generalized to other similar problems.

All sorting algorithms work on a similar concept: the sorting algorithm iterates through a list of numbers, does comparisons on pairs of numbers, and reorders the numbers based on the results of those comparisons. Consequently, by varying the comparison, we can change the way the function sorts without affecting the rest of the sorting code.

Here is our selection sort routine from a previous lesson:

Let’s replace that comparison with a function to do the comparison. Because our comparison function is going to compare two integers and return a boolean value to indicate whether the elements should be swapped, it will look something like this:

And here’s our selection sort routine using the ascending() function to do the comparison:

Now, in order to let the caller decide how the sorting will be done, instead of using our own hard-coded comparison function, we’ll allow the caller to provide their own sorting function! This is done via a function pointer.

Because the caller’s comparison function is going to compare two integers and return a boolean value, a pointer to such a function would look something like this:

So, we’ll allow the caller to pass our sort routine a pointer to their desired comparison function as the third parameter, and then we’ll use the caller’s function to do the comparison.

Here’s a full example of a selection sort that uses a function pointer parameter to do a user-defined comparison, along with an example of how to call it:

This program produces the result:

9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9

Is that cool or what? We’ve given the caller the ability to control how our selection sort does its job.

The caller can even define their own “strange” comparison functions:

The above snippet produces the following result:

2 4 6 8 1 3 5 7 9

As you can see, using a function pointer in this context provides a nice way to allow a caller to “hook” their own functionality into something you’ve previously written and tested, which helps facilitate code reuse! Previously, if you wanted to sort one array in descending order and another in ascending order, you’d need multiple version of the sort routine. Now you can have one version that can sort any way the caller desires!

Providing default functions

If you’re going to allow the caller to pass in a function as a parameter, it can often be useful to provide some standard functions for the caller to use for their convenience. For example, in the selection sort example above, providing the ascending() and descending() function along with the selectionSort() function would make the callers life easier, as they wouldn’t have to rewrite ascending() or descending() every time they want to use them.

You can even set one of these as a default parameter:

In this case, as long as the user calls selectionSort normally (not through a function pointer), the comparisonFcn parameter will default to ascending.

Making function pointers prettier with typedef or type aliases

Let’s face it -- the syntax for pointers to functions is ugly. However, typedefs can be used to make pointers to functions look more like regular variables:

This defines a typedef called “validateFcn” that is a pointer to a function that takes two ints and returns a bool.

Now instead of doing this:

You can do this:

Which reads a lot nicer! However, the syntax to define the typedef itself can be difficult to remember.

In C++11, you can instead use type aliases to create aliases for function pointers types:

This reads more naturally than the equivalent typedef, since the name of the alias and the alias definition are placed on opposite sides of the equals sign.

Using a type alias is identical to using a typedef:

Using std::function in C++11

Introduced in C++11, an alternate method of defining and storing function pointers is to use std::function, which is part of the standard library <functional> header. To define a function pointer using this method, declare a std::function object like so:

As you see, both the return type and parameters go inside angled brackets, with the parameters inside parenthesis. If there are no parameters, the parentheses can be left empty. Although this reads a little more verbosely, it’s also more explicit, as it makes it clear what the return type and parameters expected are (whereas the typedef method obscures them).

Updating our earlier example with std::function:

Conclusion

Function pointers are useful primarily when you want to store functions in an array (or other structure), or when you need to pass a function to another function. Because the native syntax to declare function pointers is ugly and error prone, we recommend you use typedefs (or in C++11, std::function).

Quiz time!

1) In this quiz, we’re going to write a version of our basic calculator using function pointers.

1a) Create a short program asking the user for two integer inputs and a mathematical operation (‘+’, ‘-‘, ‘*’, ‘/’). Ensure the user enters a valid operation.

Show Solution

1b) Write functions named add(), subtract(), multiply(), and divide(). These should take two integer parameters and return an integer.

Show Solution

1c) Create a typedef named arithmeticFcn for a pointer to a function that takes two integer parameters and returns an integer.

Show Solution

1d) Write a function named getArithmeticFunction() that takes an operator character and returns the appropriate function as a function pointer.

Show Solution

1e) Modify your main() function to call getArithmeticFunction(). Call the return value from that function with your inputs and print the result.

Show Solution

Here’s the full program:

Show Solution

2) Now let’s modify the program we wrote in quiz 1 to move the logic out of the getArithmeticFcn and into an array.

2a) Create a struct named arithmeticStruct that has two members: a mathematical operator char, and an arithmeticFcn function pointer.

Show Solution

2b) Create a static global array of arithmeticStruct named arithmeticArray, initialized with each of the four arithmetic functions.

Show Solution

2c) Modify getArithmeticFcn to loop through the array and return the appropriate function pointer.

Show Solution

Here’s the full program:

Show Solution

7.9 -- The stack and the heap
Index
7.7 -- Default parameters

200 comments to 7.8 — Function Pointers

  • stuart

    one other thing, the element arith doesn’t have a type id, so how is it compared to op in the for each loop.thanks again.

  • stuart

    in the final part of program, to loop through structure arithmeticStruc. I got confused with c++11 solution. I tried to change the logic but got stuck. can we have non c++11 solution. very good tutorial by the way.

    • Luhan

      In this part of the code

      It’s a for each loop, so the arith is the element, and it’s iterating through the arithmeticArray, so every time it iterates through the array, the element.op (character in the struct, for example, the first element of type char in the array is ‘+’), and when the array element.op matches the one passed as argument (op), it returns a pointer to the function accordingly with the match. Let’s imagine you’re executing 2 + 3, so you have the integers 2 and 3, the operator ‘+’, when you call

      it will going to compare the operator you have in the variable op(argument) with the arithmeticArray to see which function pointer should return to match the operation you want. Hope that makes sense

  • AleF

    Hello this tutorial is very good, but i have one issue here:

    This defines a typedef called “validateFcn” that is a pointer to a function that takes two ints and returns a bool.

    Now instead of doing this:

    // ugly

    You can do this:

      // clean

    In this last sentence pcfn you said its the name of the variable, but shouldn’t be TWO parameters? i cant understand this. please help. and Thanks

    • Alex

      Two variables aren’t needed. The two parameters are only needed when the function pointed to by pfcn is actually called. pfcn itself is just a pointer to a function, which is simply an address in memory.

  • Wunna

    Hi,Alex. Even though I’m not using pointer to a function,it still worked the same.

  • Angmar

    Hi, would you always recommend using the auto keyword instead?

    • Alex

      Always? No. You can’t use auto when defining a function pointer parameter.

      But if you’re using a function pointer locally inside a function (as in your example), then yes, just use auto.

  • Ben van der Meulen

    In 1e I had the solution in one line:
    [std::cout << n1 << op << n2 << " = " << (getArithmeticFunction(op))(x, y)  << "\n";]
    getArithmeticFunction(op) delivers the function that takes the integers and performs the required operation on them.
    Is the only disadvantages of my solution that it mkight be difficult to understand for other people?

  • Taksh

    Hey Alex,

    While explaining typedefs with function pointers you wrote:

    what does the pfcn written after validateFcn mean?

  • The Perplexed Programmer

    Hello Alex!

    Should’nt the above program start with #include <iostream>?

  • C++ Learner

    can you please explain what this row means? 🙂 and how we can use int keywords as function parameters?

    • Alex

      This is defining a function parameter named comparisonFcn that is a function pointer to a function that takes two integer parameters and returns a bool.

      That allows us to pass comparison functions into the sort function as a parameter.

  • John

    The syntax for an array of structs is

    But this throws an error

    Is the syntax rule that array elements of type struct must always be enclosed in curly braces {}? (I was looking through previous sections but I couldn’t find any rule about this.)

    Thanks for running this site, the quality of your presentation far supersedes the books I’m plowing through in parallel…

    • Alex

      From what I can gather, struct elements need to be inside curly braces, so the compiler knows they are an object. Non-struct elements don’t.

  • Miko

    Hello and before my problem I have a great need to say that this tutorial is best studying material I have ever read. Thank you!!!

    My problem is that when I try to make arithmeticStruct array with std::array it gives me error in here (using this "¤" to mark place) saying "too many initializer values" and I can’t find way to make it work. Is there some typo I don’t see or do I fail to understand std::array basics or something else?

    • Miko

      Forgot to mention that it works if it’s like normal array

      EDIT:

      Oh, sry for being hasty posting
      but when I added “[ ]” after arithmeticArray in std::array version it started to work like expected, but I don’t understand why it needs these “[ ]”?

      EDIT2:

      Actually didn’t work it just allowed it to compile, but everything else than “+” operator gives error in runtime.

      • Alex

        Try this:

        • Miko

          It worked, thank you. But I don’t get why you need one more of these {} with std::array than with normal array; Couldn’t find about it from std::array lesson either; Could you explain it form me?

  • jenifer

    Hey, can u explain me about the keyword "auto"??

  • AlexR

    Very glad I didn’t skip over this section. It was well written, easy to understand, and can definitely be extremely useful. Thanks again!

  • Nurlan

    Hello Alex,
    -why return type must be const if is called as  pointers to const functions?
    Below program looks that the function works as call by value.If it is call by value this problem should not have been occurred.Call by Value does not require that return type whether should const or non-const.
    - is below program call by value?

    The rule of pointer to a constant variable:
    int nValue = 5;
    const int *pnPtrt = &nValue; // POINTER TO A CONSTANT VARIABLE

    Likewise, I thought they work according the rule of pointer to a constant variable, but it does  not work.
    Here error was occured:[Error] invalid conversion from ‘int (*)()’ to ‘const int (*)()’ [-fpermissive];

    -why "int sat2()" return type must be constant?

    //===============================
    const int sat1()//return type is constant.
    {
        return 5;
    }
    int sat2()//return type is non-constant, it is error- compiler says
    {           // return type must be const
        return 5;
    }
    int main()
    {
        
         const int (*ptr1)()=sat1;// pointer to const function.
         const int (*ptr2)()=sat2;// pointer to const function.
         return 0;
    }

    • Alex

      As you’ve noticed, function pointers must match the type of the function. This includes the parameter and return types, including const. The type of ptr2 does not match the type of the function sat2.

      I’m not sure what the underlying reason is for not allowing you to make things const like you can with a standard pointer. It does seem inconsistent.

  • Hrachya

    "Note that the signature (parameters and return type) of the function pointer must match the signature of the function…"
    No.
    Function pointers use the type of the function and not its signature. The signature of ordinary functions (not templates) does not include the return type and includes the name, while the type of the function includes the return type and does not include the name.

    Example

  • Akhil

  • Milos

    Alex man, today i have 2 questions for you:

    1.How can we initialize array in quiz using std::vector?
    2.Remember me why is there "&" sign in for each loop?

    Keep up with good work, its really helpful, i was just wondering is programming starting to bother you and exhusts you, i assume that you are in it for a very long time (kinda personal question so u dont have to answer 😀 ).

    Thanks

    • Alex

      Which array? The array of function pointers?

      2) The & in this context is a reference, so we reference the original element of arithmeticArray rather than making a copy for each iteration.

  • Maher

    hi alex
    can you please explain more about this syntax
    because i don’t understand how you can use the "Fcn" function 2 times in different way , also i don’t understand how the switch just return the function address and still can be effictive.

    • Alex

      > i don’t understand how you can use the “Fcn” function 2 times in different way

      I am not sure what you mean by this. I presume you’re talking about this:

      In the top line, we’re simply assigning the function pointer returned by the getArithmeticFcn function to variable fcn. In the bottom line, we’re then invoking fcn() to call the function that fcn is pointing at.

      > i don’t understand how the switch just return the function address and still can be effictive.

      When the compiler compiles your program, it produces machine language code for each of your functions. When you run your executable, that machine language code is loaded into memory. Therefore, we can say that the machine language code that comprises a function lives at some memory address. A function pointer is simply a pointer that holds the memory address of where a function starts.

      When you invoke a function pointer (by calling it), you’re telling the CPU (jump to the function at this address). Essentially, we’re calling a function indirectly by address rather than directly by name.

  • saeid

    i really hanged. i got confused in this lesson and don’t know how quiz get solved in this way . i got nervous

  • Omar Sosa

    Hi Alex,
    first of all, thank you very much for these tutorials, they have been extremely helpful!!

    Question:

    I tried to define my array of arithmeticStructs like this:

    but my compiler won’t accept the syntax.

    So, if I’m stubborn and want to use std arrays instead of built-in arrays, how should I define my array?

    Thanks again for all your help!

    Best,
    Omar

    • Alex

      Visual Studio 2015 accepts this:

      • Omar Sosa

        Sweet! Thank you! 😀

        • Elruin

          You should be able to use it like this, i think it’s easier to read:

          correct me if i am wrong

      • Alexander Kindel

        Do you know why exactly it’s necessary to add

        before each individual struct in the initialization list when using std::array, when it isn’t necessary for built-in arrays? As far as I can tell, that’s not something I could have known to expect based on the lesson about std::array, and it’s not obvious how I could have reasoned my way to the syntax that works on my own either. I might have expected initializing the four structs separately and then inserting the names I gave them into the array initializer list to work, but something like

        is not the same as initializing the struct because no variable name is provided, right? Perhaps it’s syntax that is specially defined for std::array?

        • Alex

          This is a good question, and the short answer is that I’m not really sure.

          Here’s what I can tell you. When you initialize a fixed array, the syntax for that is defined as part of the language:

          In this case, I think the compiler reasonably assumes that each subelement is an initializer for the arithmeticStruct element.

          However, when we use a std::array, the syntax looks similar:

          But under the hood, this behaves very differently. After doing some research, it looks there is a way to define the elements without the explicit arithmeticStructs (at least using Visual Studio), but the syntax is non-obvious:

          Why this two-outer-brace syntax works but the one-outer-brace syntax doesn’t is still a mystery to me.

  • Janeta

    Hello Alex,

    I have a question regarding quiz 1d).
    In 1c) we created a typedef named arithmeticFcn to use it for function pointer that takes two integers and returns an integer (typedef int (*arithmeticFcn)(int, int);) . Correct? So I can’t understand why do we use that typedef for getArithmeticFunction(), which is a function that takes a char and returns a pointer?
    Thank you very much for the great tutorial!
    BR,
    Janeta

    • Alex

      First question: Correct.

      Second question: You’re passing a char to function getArithmeticFcn() in order to select which function you want. getArithmeticFcn() returns a pointer to function add, subtract, multiply, or divide. That returned function pointer is of type arithmeticFcn, which matches the signature of functions add, subtract, multiply, and divide. arithmeticFcn is not meant to point to function getArithmeticFcn(), which has a different signature.

  • Tomas

    What do you think of this way of interpretation? Once i managed to think of this code i thought you have done it the same way until i realized you did not.. Hehe

    Anyway, I got to say one more time, this site is insanely good.

    • Alex

      There isn’t really any advantage to doing things this way -- you’re creating a pointer to a function and then using that pointer immediately to call the function. You might as well just call the function.

      The advantage of pointers to functions is that you can pass them as parameters or return values, which you don’t do at all here -- so while you’ve got the mechanics down and this does produce the right value, you didn’t prove your understanding of why these are useful in the first place.

  • Gapo

    static arithmeticStruct arithmeticArray[] {
        { ‘+’, add },
        { ‘-‘, subtract },
        { ‘*’, multiply },
        { ‘/’, divide }
    };

    If an array is of type struct, I can sort the elements inside of array the same way I sorth the elements in a structure ?

    • Alex

      Not sure I understand what you mean by “the same way I sort the elements in a structure”. That said, if you have an array of structs, you can sort the array, but you’ll need to figure out what struct element to sort it on.

  • Hang

    About the selectionSort() function:
    I like the example you give us. It helps me a lot. Just to mention one trivial thing, after you have defined a third parameter, which is bool (*comparisonFcn)(int, int), the argument could be either asconding or descending. So it would be better if the index name could be changed properly from smallestIndex to some name else. When I tried to go through the program with a descending argument, the index name smallestIndex is confusing.

  • Ninja

    Wow, this is the hardest thing I’ve come across so far in programming. I had to reread it a bunch of times and it took a while to wrap my head around it. I found that the alternate synax for dereferencing a function pointer fcn(x, y) is inconsistent with what I learned and it caused me more confusion. I find (*fcn)(x, y) easier to remember and understand because it makes more sense to me. Thanks for the awesome tutorials Alex! I really appreciate it. I know for a fact that if my teacher tried to teach me function pointers, I would never understand it as well as I do from reading your site.

  • Kılıçarslan

    Alex, you should add this as the c++11 way of using alias for function pointers.
    Old way:

    New way:

    Do you agree?

  • Matt

    Alex,
    In your final quiz solution, why did you decide to make the array static?

    • Alex

      Because the instructions said to. 🙂 Static in this context just makes the array have internal linkage, so you can’t access it from another file. It’s not strictly necessary.

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter