function pointer assignment and call in c++?

后端 未结 2 476
小鲜肉
小鲜肉 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: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
    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
    

提交回复
热议问题