Search code examples
c++functionpointersimplicit-conversion

C++ What's the difference between function_pointer and &function_pointer?


I was reading some documentation, and I saw that one can initialize function pointers with and without the '&':

    #include <iostream>

    int No() { return 5; }

    int main() {

        int (*f)() = &No; //method 1
        int (*f2)() = No; //method 2

        std::cout << (*f)() << std::endl; //prints out 5
        std::cout << (*f2)() << std::endl; //prints out 5

        return 0;
    }

I can't see the difference between the two methods. Is one "better" than the other? Are there any differences between those two?


Solution

  • Function designators are implicitly converted to pointers to the function types.

    From the C++ Standard (4.3 Function-to-pointer conversion)

    1 An lvalue of function type T can be converted to a prvalue of type “pointer to T.” The result is a pointer to the function

    So these declarations

        int (*f)() = &No; //method 1
        int (*f2)() = No; //method 2
    

    are equivalent. In the first declaration the function designator is converted to pointer explicitly while in the second declaration the function designator is converted to pointer implicitly.

    In the call of the function in this statement

    std::cout << (*f)() << std::endl;
    

    using the expression *f is redundant because again the function designator *f is converted to pointer. You could just write

    std::cout << f() << std::endl;
    

    If you want you can even write

    std::cout << (*******f)() << std::endl;
    

    The result will be the same.

    Here is a demonstrative program.

    #include <iostream>
    
    int No() { return 5; }
    
    int main() 
    {
        int (*f)() = &No; //method 1
        int (*f2)() = No; //method 2
    
        std::cout << f() << std::endl; //prints out 5
        std::cout << ( *******f2 )() << std::endl; //prints out 5
    
        return 0;
    }
    

    That is dereferencing the pointer *f2 yields lvalue of the function type that in turn again is converted to function pointer.