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.

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:


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
7.7 -- Default parameters

185 comments to 7.8 — Function Pointers

  • 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


      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 “[ ]”?


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


  • 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 😀 ).


    • 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!!


    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!


    • 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!

    • 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

    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.

  • Sivasankar

    Hi Alex,

    By reading this lesson, I finally got an understanding on how register callbacks mechanisms might be implemented in the Teamcenter PLM tool that is built in C++. Thank you for that.

    I got confusion at below line in this lesson.
    "One interesting note: Default parameters won’t work with function pointers."

    But in "providing default functions" section, a code snippet is put as below which I hope ascending is the default argument for comparisonFcn function parameter. And user may call with only the 1st 2 arguments if I’m correct.

    Could you please explain ?

    • Alex

      Yep. Two separate concepts.

      When defining a function, you can have function pointers as parameters, and those function pointers can have default values (see the selectionSort() example above). This works just like any other defaulted parameter.

      If you call any given function normally (not through a function pointer), any default parameters will resolve as you’d expect.
      If you call any given function through a function pointer, any default parameters will not resolve, so you’ll always have to pass in values for all parameters in this case.

      I’ve update the lesson text slightly to try to make this clearer.

  • Matt

    Under "Assigning a function to a function pointer", you wrote:
    "Note that the signature (parameters and return value) of the function pointer must match the signature of the function."

    Should "return value" actually be return "type"?

  • Yash Verma

    I was understand function pointers from C++ Primer. So I decided to read it from the tutorial and now all my doubts are clear. Thank you for this tutorial.

  • Mauricio Mirabetti

    Alex, I’m following your course and I’m actually learning. Thanks again (and again).
    Regarding typedef to simplify functions declarations that return function pointers, I totally get it. But I haven’t seem an example where typedef is not used, with the same functionality. Is it possible?
    I include a code where line comments show originals (working fine) and what I understand would it be without using typedefs:

    Got several errors, first being C2091 "function returns function" (function returning function is not allowed), on this line below:
    int(*getArithmeticFunction)(int,int) (char oper) {

    Thanks a lot!



    I enjoyed this chapter. Thank you.

    I have one question to ask.
    If doesn’t "typedef" or "std::function" , How could we declare a function which return function pointer??

    • Alex

      The syntax to do this is super ugly. Here’s how you’d write a function that takes a bool and returns a pointer to a function that takes two integers and returns a bool:

  • Nephilimac

    A word "unintentially" below the 3rd code sample may be aimed at "unintentionally" or "inadvertently".

  • Chris


    i have question about number 2c, why we need return add at bottom of getArithmeticFcn function? i think its not necessarry because if the "op" variable is + so arith.fcn must be "add" and it is sure the input is just beetween that 4 operation because we have a do-while loop to make sure it, isnt it?

    Thank you.

    • Chris

      sorry double post, there is more question i want to ask.
      if i make function pointer argument just like normal function (argument "int x") it seem the compiler not complaint or warning me. there is use for this? int (*ptrFcn)(int x)

    • Alex

      What happens if none of the arith.op match the op parameter?

      It would probably be better to assert out or something, but in this case, I’ve just assumed the user meant to add (for simplicity).

      • Chris

        but i think op parameter always will match with arith.op because in getOperation() there is do-while loop and it make sure the op parameter just can have + or - or * or / and arith.op just have them too.

        • Alex

          Yes, in this particular case, getOperation() will ensure that op has a valid value. But when you’re writing functions, you should never assume anything about the inputs.

          For example, what if I updated getOperation() to also support modulus (%)? In that case, getOperation() would allow % as a valid input, but if I forgot to update arithmeticArray then nothing would match in getArithmeticFcn().

  • Vlad

    Hello Alex

    I can’t compile this part:

    I get this:

    There is a caret pointing to the closing bracket around (foo) in the static_cast. I am using archlinux x64 (codeblocks or console "g++ -o …", same thing). Is this a g++ whim?

    • Alex

      Hmmm, I”m not sure. Does the following work?

      • Vlad

        Yes, that works. Also std::cout << foo, and both return 1. Just now I remembered about the other type casts, so, looking at the list you gave, the "reinterpret" one seemed more appropiate, so I tried it, and, to my surprise, it works. At least, it returns an address: 0x400796. Maybe it’s some new change in the compiler version?

        • Alex

          It seems like reinterpret_cast to void would be a valid way to print a normal function’s address. This doesn’t work for member functions though (which is fine for these examples since these aren’t member functions).

  • Arslan

    foo() in the first case is an lvalue function type. Not a pointer to a function.

    lvalue functions get implicitly converted to pointer-to-functions when passed to a non-reference parameter. So in the sorting code in your post, ‘ascending’ and ‘descending’ are lvalue functions types, but are implicitly converted to pointer-to-functions when passed to the sort function.

  • Rob G.

    I finished 7.8_e and now have a working primitive calculator!!

    I used auto for determining my function type above as well as the caller (below):

    So its up and working fine:

    But what did my type(s) end up being that were predicted by the auto fx?

    • Alex

      Your auto is inferring type int(*)(int, int) (what you typedef’d with arithmeticFcn).

      It’s best practice not to auto your function return types (it makes it harder for callers to discover what type your function is returning).

      • Rob G.

        It’s best practice not to auto your function return types

        I agree but couldn’t get the result any other way. Would you mind modifying and posting my code with changes you mentioned so it works without auto keyword? I think its only a few.This is key to my understanding. I would rather master this aspect than rely on auto.
        Thx in advance

        • Rob G.

          "Would you mind modifying and posting my code" … that sounded terrible sorry. Just modification to the points of interest. 🙂

          • Rob G.

            Well I didn’t think I could do it, but auto keyword removed successfully. arithmeticFcn type replacing auto keyword. A typedef is a type.

  • Rob G.

    Alex I get an error with the return pointer addresses: I’ve tried them without & and with, but I still get errors. Assume I have included all of the other functions necessary to run the program to save space here.

    ..srcmain.cpp: In function ‘int* getArithmeticFunction(char)’:
    ..srcmain.cpp:28:21: error: cannot convert ‘int (*)(int, int)’ to ‘int*’ in return
    case ‘+’ : return &add;
    … the same error for -,/,*

    • Rob G.

      To overcome the challenges above I changed the int * get…   to "auto".
      I also had to change compiler settings to ISO C++1y. I don’t line just auto-ing hit; I’d like to know what the proper type is.

      • Rob G.

        Still having a hard time with this:

        Where are they returned to and how do we know what are we retrunig.

        • Alex

          The return values are returned to the caller just like any other return value. The caller can then do what it wants with those values (including ignore them).

          You know what you are returning because you have return statements indicating what is being returned in each case.

    • Alex

      Yes, your getArithmeticFunction function is declared as returning a pointer to an integer. However, add, subtract, divide, and multiply have type int (*)(int, int).

      You’ll need to update the return type of your getArithmeticFunction to match the type of the function you’re wanting to return.

      • J3ANP3T3R

        bool validate(int x, int y, std::function<bool(int, int)>); // std::function method that returns a bool and takes two int parameters

        i don’t see any temporary variable for the function variable

        std::function<bool(int, int)>

        how do i use it from within the function ?

  • Rob G.

    Alex you mentioned that I was using pointers to functions, not nested loops. Could you give a brief example of a nested loop (maybe from my code where I pass the pointer)? Also, any recommendations on the legibility of the code? I’ve got indentations going -- other suggestions? Thx for your time.


    • Alex

      > Alex you mentioned that I was using pointers to functions, not nested loops

      No, I said you were using pointers to functions, not nested _functions_.

      Using a nested loop wouldn’t make sense here.

      • Rob G.

        I meant nested functions --
        Not nested loops.

        • Rob G.

          Hi Alex, I meant nested functions not loops -- sorry. If you have anything to say abt how this exercise could relate to nested functions, I’d lke to hear it. If not -- onward. This is a great website and thank you for your time. I have thus far learned so much.

          • Alex

            Nested functions are illegal in C++ (though there are some workaround via classes/lambdas/closures), so there isn’t much to say here, actually. 🙂

  • Rob G.

    I finally get it! The key to understanding for me was that we are creating functions within functions. I tried doing this other ways, but found that this was what function pointers were suited for. I was either asleep at the wheel when you mentioned this above, or it needs to be made more clear in the start of the exercise.

    cool !

    do stuff
    do other stuff

    • Alex

      It’s misleading to say we’re creating functions within functions (that sounds like nested functions).

      What we’re doing is using a pointer to hold the address of a function. Then we can dereference that pointer to call the function the pointer is pointing to!

      • Rob G.

        I stand corrected, but I basically get the exercise. I’m still scratching my head a little on when to use a pointer to function, but its immediate utility to me is to dereference the pointer to another function while in a function already. Yes, very cool.

  • Sachin Singh

    Hey, I’m just wondering why didn’t you mention the functional header. It makes defining function pointers a lot cleaner.

    Here pf can point to a function that returns a double and has one parameter which is a double as well.

  • Rob G.

    Ok, strategy: when faced with multiple functions, how does one know whether to use the function pointers or more standard setup of referencing the functions as needed?

    • Alex

      I always use regular functions unless I need to store functions in an array or pass a function as a parameter to another function.

  • Rob G.

    Hi Alex,

    I was getting this to work with ints which I no longer need. Trying to use void since I have no return value.
    What is wrong with my code? The fx count_up is never called. Thx in advance.

    • Alex

      Your function is running just fine, but your loop condition is failing immediately since 10 < 3 is false. If you switch your 10 and 3 parameters, you'll see it's working as you expect.

  • Satish

    Hi Alex,
    I am having a hard time understanding the below line of code, and would appreciate your help:

    arithmeticFcn fcn = getArithmeticFcn(op);

    Here arithmeticFcn takes two integer values as parameters and return type is int. However, function getArithmeticFcn takes char as an input. Could you please explain how this works?

    • Alex

      Sure. In this case, getArithmeticFcn(op) is just a normal function call. So when we call getArithmeticFcn(‘+’), the function executes, and the switch statement inside returns a pointer to function add. This return value (function add) is then assigned to variable fcn.

      There’s no mismatch here since we’re not trying to assign function getArithmeticFcn() (which takes a char parameter) to variable fcn (which expects two int parameters) -- we’re assigning the return value from getArithmeticFcn() to variable fcn.

      Make sense?

      • matt senko

        i have the same issue of wrapping my head around this.

        arithmeticFcn fcn = getArithmeticFcn(op);

        i get that we are callnig getArithmeticFcn(op) to get add, subtract, multiply, divide.  what i dont get is how do you know you are getting a pointer to those functions?  can you please try and explain that more to me, im getting stuck on it.

  • Rob G.

    Hi Alex, when I create a function ptr, I have to specify the type and arguments:

    However when I call the function using it with type int and including the arguments
    an error occurs and I have to remove the type to make it work. Why is this so?

    • Alex

      Same as with normal variables. You need the type when you declare the variable so the compiler knows what kind of variable it is (in this case, to tell the compiler it’s a pointer to a function taking an integer parameter and returning and integer).

      However, whenever you use the variable, you don’t need to include the type again.


  • Rob G.




    worked fine. Thx!

  • Rob G.

    Alex I am trying to create a function ptr to a void type with no arguments. I am getting no errors but the void function characters aren’t printing out: its not going to the function.

  • Anonymous

    Hi Alex, a couple of questions:

    1) Why do we need the <static> keyword when declaring <arithmeticArray>? From what I recall, since we are declaring the array outside of any functions, so globally, this restricts the array to internal linkage. Is that the only reason it is used here?

    2) In the for loop, should we not be using a reference for each element in the array since they are structs? Such as

    for (auto &arith: arithmeticArray) {…}



  • Connor

    Hi Alex, WRT Q2a.

    I created my struct as:

    but when I try to initialise the array in Q 2b. as

    it gives me the error "no instance of constructor "arythmeticStruct::arythmeticStruct" matches the argument list ". When I don’t give

    a default value then it compiles.
    I don’t understand why this is.

    • Alex

      I’m actually a little surprised that this doesn’t work. It must be a side effect of how the non-static member initialization was implemented.

      For now, just leave your struct uninitialized. Defaulting it to ‘+’ doesn’t really make sense anyway.

  • I have been studying c++ and in particular this tutorial on and off for around 18 months now and find it really helpful.  The first time I read this page I didn’t get it at all, but after moving further through the tutorial and returning to various pages as and when I thought it necessary to brush up or advance my skills, I returned to this page and with my added experience and knowledge I suddenly got it.  The problem that I had though was that I was trying to apply this knowledge to member functions and simply could not get it to work.  Unless I have missed it, I cannot find anything about pointers to member functions and would like to see an article on the subject.  I have taken a guess at what the code should be and it works when I compile it, but I would be interested to know if there are any particular downsides.

    Here is my header

    my .cpp file

    and my main

    It appears to me that pointer to member functions have to be grafted on to classes rather than being properly built into their functionality.  Would I be right in assuming this?

    • Alex

      I’ve taken a note to add a section about pointers to member functions once we cover that member functions are. Pointer to member functions are a little different than pointers to functions because of the implicit “this” pointer parameter. Consequently, pointers to member functions need to contain the class scope qualifier, so the compiler knows what type *this should be. And because a pointer to a member function can only point to functions within the specified class, they aren’t used all that often.

      • I am writing something that involved an over the top switch statement to handle user input and it just seemed a little easier to read and maintain using function pointers instead.  I am very much still learning but I am also learning on the fly because I am writing a sizeable program that interfaces with a database.  Somehow my code just seems a bit messier with switch statements than it does with function pointers although perhaps that is just because I have not developed a proper style yet and function pointers discipline me better.

    • Rob G.

      Your history concerning your c++ road traveled was very inspiring. Thanks for sharing that.

  • Daniel P.

    I have a problem with the first part of the quiz. I declared a pointer to an int function:

    then to initialize it  I used a function like this:

    and in main(), I call the function like so:

    The problem is that the pointer operation isn’t innitialized. Anyone knows what I’m doing wrong? Thanks

    • Alex

      The problem here is that you’re passing your function pointer by address (which is essentially a pass by value of a pointer). Because of this, when your function changes the value of parameter operation, that isn’t passed back through the argument.

      There are two ways to fix this:
      1) Pass your pointer operation by reference
      2) Return your operator as a return value rather than a function parameter

      • Daniel P.

        Thank you very much :)! I got confused because of the way we use arrays in functions but I see now that you have to dereference the pointer to change the value of the parameter. I’d like to take the opportunity to thank you for these very well-made tutorials and all the effort you put into them, it shows.

  • Soul

    Thanks for your great lessons, this website has been awesome.

    Could you also please tell me which lesson to go back to, to understand the answer to 2b? I don’t understand how to tie two things together for one choice from the array (for instance: {‘+’, add}, I don’t understand how the array understands the two things together as one element).


    • Alex

      You’ll want to review lesson 4.7 -- Structs.

      Each array element of arithmeticArray is a single struct. Each struct contains two values (the op and the fcn).

      So we use the array index to pick the struct, and then use the member selection operator to determine whether we want op or fcn.

  • Bede

    Hi Alex, I found a small typo: "as a argument" -> "as an argument"

  • BlueTooth4269

    Just wanted to point out that your solution for 1a will not work assuming the user enters more than one character for "operator".
    The loop will go around several times with cin feeding off the additional characters, resulting in "Enter operator" being printed several times without a cin happening.

    • Alex

      Yes, typically the quiz answers given here don’t have robust error handling, because doing so makes the solutions significantly more complicated and obscures the point of the lessons. It’s a tradeoff for simplicity.

  • Shmid

    Oh my god this solves so many problems.

  • Pisces

    This returns 1 with codeblocks. In fact, any function name when passed to cout without () returns 1 on my machine. Why?

    • Alex

      It looks like GCC is converting the function pointer to a boolean before printing it (hence the value of 1). Visual studio prints it as a hex value. My guess is that GCC is interpreting the C++ standard strictly, whereas Visual Studio is doing something non-standard to better reflect the programmer’s likely intent.

  • 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 C++ code inside [code][/code] tags to use the syntax highlighter