Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

usage on c++ function pointer

I'm a newbie to C++, learning pointer of function recently, a little confused by usage of pointer of function;

I practiced the following code:

#include <iostream>
#include <sstream>
using namespace std;

int subtraction(int a,int b){
    return a-b;
}

int main(int argc, const char * argv[])
{

    int (*minus)(int,int)=subtraction;
    cout<<minus(5,4);

    return 0;
}

it works well; so,I try a little variation:

#include <iostream>
#include <sstream>
using namespace std;

int subtraction(int a,int b){
    return a-b;
}

int main(int argc, const char * argv[])
{

    int *minus(int,int)=subtraction;//only here different!
    cout<<minus(5,4);

    return 0;
}

I practiced it in Xcode on Mac,it give me Error:

Illegal initializer (only variables can be initialized)

but I think compiler can recognized the two is same,why must have a pair of parenthesizes?

like image 202
Wei JingNing Avatar asked Dec 06 '22 05:12

Wei JingNing


1 Answers

In your original code

int (*minus)(int,int)=subtraction;

declares minus as a function pointer that takes parameter int, int and returns int.

In your second code

int *minus(int,int)=subtraction;

declares minus as a function that takes parameter int, int and returns a pointer int *.

You can use a function name(which is automatically converted to a function pointer) to initialize a function pointer, but you can't initialize a function.

like image 105
Yu Hao Avatar answered Jan 01 '23 13:01

Yu Hao