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:


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

Many comparison-based 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 algorithm 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 versions of the sort routine. Now you can have one version that can sort any way the caller desires!

Note: If a function parameter is of a function type, it will be converted to a pointer to the function type. This means

can be equivalently written as:

This only works for function parameters, not stand-alone function pointers, and so is of somewhat limited use.

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 caller’s 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:

Note that you can also type alias std::function:

Type inference for function pointers

Much like the auto keyword can be used to infer the type of normal variables, the auto keyword can also infer the type of a function pointer.

This works exactly like you’d expect, and the syntax is very clean. The downside is, of course, that all of the details about the function’s parameters types and return type are hidden, so it’s easier to make a mistake when making a call with the function, or using its return value.


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 using std::function. In places where a function pointer type is only used once (e.g. a single parameter or return value), std::function can be used directly. In places where a function pointer type is used multiple times, a type alias to a std::function is a better choice (to prevent repeating yourself).

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 type alias named arithmeticFcn for a pointer to a function that takes two integer parameters and returns an integer. Use std::function.

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

7.9 -- The stack and the heap
7.7 -- Default arguments

477 comments to 7.8 — Function Pointers

  • Lokesh

    In the “strange” comparison functions example inside evensFirst():

    should be

    (bracket for second equality comparison) according to the semantics. Though the first one would also work but it does not convey proper meaning.

  • Benjamin

    Trying to convert pointer to a function or pointer to member function to a void pointer will cause build/compile error
    -- and is illegal in C++ (officially).
    It deserves to be mentioned as many people can be misleaded on the following issue.

    Anyway, I really appreciate you for your fantastic tutorial.

  • richie_rich

    Default argument with function pointer

    #include <iostream>
    using namespace std;

    int goo(int a=0)
        return 8;
    double foo()
        return 8.8;
    int main()
    int (*fptr)(int);
    fptr = goo;
    cout<<(*fptr)()<<endl; // if int a is default argument should i need to pass it in function call with function pointer please answer


    • Alex

      This is an interesting point. Default arguments 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 arguments can not be resolved. You'll explicitly have to pass in a value in this case.

  • When you are illustrating implicit dereference, your code is as follows:

    However shouldn't

    actually be


    Thank you for the great website!

  • Gopal

    Can we simply pass comparison operator (e.g. == or > or < or <= or >=) to function from calling function?

  • Hritik

    Thanks! Keep it up! God Bless Ya

  • Alex, I have some serious confusions:

    In the selection sorting program above, the third parameter is a pointer to a function that takes two int parameters and returns either true or false, right? In function main(), we are calling SelectionSort() with arguments The array, its size and Ascending/Descending Function's address, right?.  But what about those two comparison functions. When are they called?

    The typedef here is very confusing for me:

    typedef's syntax is "typedef int name" for a typedef of ints. But what is happening above? I think we are defining a typedef for a pointer to a bool type function having two int pararmeters. Where is the alias name? Can you please elaborate. This is the most confusing thing I have found so far in this tutorial. Thanks.

    • Alex

      See the line in the example that says "// COMPARISON DONE HERE"? That's where the comparison function (that is passed in as a function pointer) is _actually_ called. And it's called just like a normal function is. However, it will execute whichever function we passed in.

      You are correct about what the typedef means. The name of the typedef is pfcnValidate. So when we write pfcnValidate, we really mean a function that takes two int parameters and returns a bool.

  • Antonyo

    Hi Alex!
    I have a question.
    I change bool "(*pComparison)(int, int)" to "bool pComparison(int, int)"
    and my programm was working good. Why we need the pointer in this cays?

    • Alex

      You actually don't need the asterisk in this case. When it comes to function pointers parameters, C++ will accept an asterisk-less version as well.

      Note that this syntax only works for function pointer parameters (you can't declare function pointer variables that way).

  • Tareq Mansour

    Thanks, :)

  • RaceFan

    function signature should have been introduced in the section on function overloading.

    Pointers are a piece of cake if you've done any Assembly programming...

  • It's like magic . Great !!!

  • mohsenhs82

    Hi Alex
    Great job, Great Tutorial, and an Excellent example.

    merry Xmas.

  • Matt

    Great tutorials Alex although all this pointer stuff is pretty confusing. I'd like to see some questions at the end of some of these though. I would have a better understanding of the concepts and a memory of the syntax if I had to do some of this myself; a suggestion if you have time.

  • george

    Is function pointer the only way to pass a function as a parameter to another function?

    • Alex

      No, but it's definitely the easiest and probably the fastest.

      But, for example, C++11 comes with a class called std::function (in the functional header) that can also be used to pass functions as parameters. However, because std::function is designed to handle a lot of other use cases besides just passing a function, it can be quite a bit slower.

  • Srivatsan

    hi Alex,

    What exactly does it mean when you say the name of the function is a pointer?? A pointer to a variable, I understand, holds the address where the variable is stored. What is stored in the address that the name of the function points to?

    Great tutorial. Thank you.

    • Alex

      A pointer to a variable holds the address of the variable.
      A pointer to a function holds the address of the function's code.
      Since a function's name is essentially a function to a pointer, the function's name points to the address where the function's code lives.

  • Blaji

    Hi, I would like to add some more points. How do we declare a pointer to a function which returns a pointer to a function ? (function pointer returning function pointer). Here we go.. Explained by sample code below. Hope its clear.

    void foo()
    printf("Im foo");

    typedef void (*retType)();

    retType FuncRetFuncPtr()
    printf("FuncRetFuncPtr calledn");
    return foo; //returning function pointer

    retType (*fptr)() = FuncRetFuncPtr;
    void (*catchfoo)() = fptr(); //catchfoo-holds return val of FuncRetFuncPt

    catchfoo(); //prints "im foo". for confirmation :)

  • Murka

    Member functions are sometimes a pain to use, but typedefs make even such fugly syntax readable.


    So remember, typedefs are your friend. I still haven't found out how to write the above without one, but am interested how it would look.

  • awsome post..i love it.. :)

  • Solved !

    • Ravi


      Nice way of explaining the Function pointers.

      I tried to compile the code given up and I am still getting this error

      error: prototype for ‘void Kas::secondfunction(int (Kas::*)(int), int)’ does not match any in class ‘Kas’
      error: candidate is: void Kas::secondfunction(int (*)(int), int)

      • Benjamin

        Greetings form South Korea.
        Indeed fixed.
        Definitely works (at least on GNU GCC Compiler).


      • Benjamin

        Sorry, still there was a bug so it worked on some compiler -- plus some typos.
        I fixed the code that it worked on
        Simple scoping issue was the fundamental issue here.

  • I have a problem:

    I write a class.

    There is a function, member of this class.

    There is another function, member of this class, takes a "function pointer" as parameter.

    Inside this class there is also a third function and it calls the second function with a function pointer to first function as parameter.

    Here is the code:

    how can I call the second function?

  • Its strange you didn't cover pointers to member functions...anyways great tutorial overall.

  • ROCKIN!!! Been trying to get my head around function pointers for ages!!!

    Now I get it!!!

    Probably forget again tomorrow, but at least I can come here and look it up again!

    THANK YOU!!!!

  • Ryan

    You left two things out of your full example.

    1. You forgot to include iostream needed to define the 'cout'


    You forgot to add 'using namespace std;' thus cout doesn't work here.

  • fernando

    Should the function call not return some value ?

  • Simon

    bool EvensFirst(int nX, int nY)

    Alex your comments are incorrect in this function as pointed out by Stuart.

    You can either change the if statements to match the comments or change the comments to match the statements.

    You need to change the 1st comment with the second, and vice versa .
    Stuart's changes also correct the anomalies.


  • Stuart

    How is bool working here? How is the return false and return true working to return the integers in different orders?

    • Stuart

      I get it now, after rewriting the EvensFirst function to this:

      I got mixed up and didn't realize that nX % 2 actually means that nX is NOT divisible by 2 and !nX % 2 means that it IS divisible by 2.

  • shyan

    typedef of function pointer looks complex.
    no typedef variable. how it assumed that pfcnVlidate is typedef... confuse


  • Renu

    Syntax of typedef is:
    typedef type alias name;

    How does that map to:
    typedef bool (*pfcnValidate)(int, int);

    This seems complex.


    • This is one of the really ugly parts of C++. Basically, the type is a pointer to a function returning a bool and taking 2 int parameters, and the name of the typedef is pfcnValidate.

      I suspect they did the syntax this way to mimic the way actual function declarations look, but I agree that it doesn't map to the typedef syntax in a very intuitive manner. It's one of those things I have to look up how to do every time I need to do it... but that's still better than not using typedefs at all.

      • J3ANP3T3R

        how do we use std::function since it is preferred than typedef i used it on the quiz but the compiler would not accept it.

        std::function<int(int, int)> arithmeticFcn;

        arithmeticFcn getArithmeticFcn(char op)


        • J3ANP3T3R

          oh never mind i declared mine in a header file and included the header in the include section. seeing as typedef above was placed just outside of the functions (global scope?)

          ill just use std::function there too.

          EDIT: It still wont accept std::function placed exactly in the same spot as typedef above.

        • Alex

          Try one of these instead:

          or, since std::function isn't as messy to use directly:

          • J3ANP3T3R

            oh thanks. the first example would still end up using typedef afteral however the second one looks great. im trying to avoid using typedef as suggested. i was kind of expecting i would be able to do to a function pointer what typedef could since std::function seems to be suggested as an alternative to typedef. like declare a variable function pointer that i can also use as a return type for the function just like above with arithmeticFcn. can we do that with std::function ? so that i can use a simple looking variable "arithmeticFcn". however std::function<int(int, int)> getArithmeticFcn(char op) is great thanks.

    • Saurabh

      A typedef statement is nothing but a 'typedef' keyword followed by a Declaration.
      A Declaration always consist of -
      1. One variable name
      2. One basic type | e.g. char, int, signed char etc
      3. Zero or more derived types | Derived types are : * - pointer, [] - array, () - function

      Below are few declarations -

      Now, If we prefix each of these Declarations with a 'typedef' keyword, all of these will become valid typedef statements.
      All of these would have a form like this -
      typedef <a Declaration>
      or we can say -
      typedef <combination of (Variable name, Basic Type, Derived Type)>

      Now let's try to find the alias name from these typedef statements -

      So, the rule is simple - Just pick up the Variable name from the declaration which follows the typedef keyword to get the alias name.
      And the Type of this alias name in the typedef statement will be the same as the type of the variable in the declaration part.

      int id;            // I read this as - id is a variable of type int
      typedef int id;        // I read this as - id is an alias name to the the type int

      Finally, if now you are also able to visualize typedefs with the new perspective -

      Now, let's see how we use these typedefs in our codes -


      Cheers :)
      A many Thanks to Alex for :)

  • Ainsley

    hi i enjoyed the read

Leave a Comment

Put all code inside code tags: [code]your code here[/code]