Reputation: 65
I am trying some random declarations of array pointers and function pointers together. I was struck here.
#include<bits/stdc++.h>
int add(int a,int b){
return 1729; }
int main(){
int (abc)(int,int);
abc = add;
return 0;
}
The emitted error is:
cannot convert 'int(int, int)' to 'int(int, int)' in assignment
But as both abc
and add
are of the same type, why should it convert? Or is it possible to assign functions to new variables? If so, how to do that?
Upvotes: 3
Views: 1511
Reputation: 170173
int (abc)(int,int);
It's not a function pointer. The extra parentheses don't matter in this case, and it's equivalent to
int abc(int,int);
Which is a function declaration, that C++ allows you to put almost anywhere (like the body of another function). Your code doesn't compile because you attempt to assign one function name to another.
To get a pointer, you need pointer syntax
int (*abc)(int,int);
Where, this time, the parentheses are required, else you get a function declaration with an int*
return type! And now the assignment will be well-formed.
Upvotes: 14