function pointer assignment and call in c++?

后端 未结 2 475
小鲜肉
小鲜肉 2021-01-18 23:25

I know when we use the name of a function as a value, the function is automatically converted to a pointer. look at following code:

int print(int a)
{
    re         


        
相关标签:
2条回答
  • 2021-01-18 23:50

    print is a function, but it is implicitly convertible to a function pointer type. Quoted from cppref:

    Function to pointer
    An lvalue of function type T can be implicitly converted to a prvalue pointer to that function. This does not apply to non-static member functions because lvalues that refer to non-static member functions do not exist.

    So, in your case:

    int (*p)(int) = print; // Conversion happens.
    int (*q)(int) = &print; // Conversion does not happen.
    

    Implicit conversion kicks in automatically when it is needed to make the program compile, and is not applied otherwise.

    With respect to function calling, it is about the built-in function call operator (). According to cppref, the built-in function call operator is applicable to both an lvalue expression that refers to a function and a pointer to function. In your case:

    p(8); // The function call operator is applied to a pointer to function.
    (*p)(8); // The function call operator is applied to an lvalue reference to function.
    

    For your reference (emphasis mine):

    Built-in function call operator
    A function call expression, such as E(A1, A2, A3), consists of an expression that names the function, E, followed by a possibly empty list of expressions A1, A2, A3, ..., in parentheses. The expression that names the function can be

    a) lvalue expression that refers to a function
    b) pointer to function
    ...

    0 讨论(0)
  • 2021-01-18 23:59

    print is not a pointer. Its type is int(int), not int(*)(int). This distinction is especially important in type deduction

    auto& f = print;   //type of f is int(&)(int), not int(*(&))(int)
    template<typename Func>
    foo(Func& f);
    foo(print);  //Func is deduced to be int(int), not int(*)(int)
    

    Analogous to arrays, you cannot copy a function "by value", but you can pass around its address. For example,

    int arr[4];     //the type of arr is int[4], not int*
    int *a = arr;   //automatic array-to-pointer decay
    int (*a)[4] = &arr;  //type match 
    int (*p)(int) = print;  //automatic function-to-pointer decay
    int (*p)(int) = &print; //type match
    

    Now when you call print through p,

    p(8)     //automatic dereferencing of p
    (*p)(8)  //manual dereferencing of p
    
    0 讨论(0)
提交回复
热议问题