3

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?

StoryTeller - Unslander Monica
  • 148,497
  • 21
  • 320
  • 399
girish
  • 63
  • 5
  • Possible duplicate of [How do function pointers in C work?](https://stackoverflow.com/questions/840501/how-do-function-pointers-in-c-work) – Blaze Jun 11 '19 at 06:52
  • 5
    Unrelated to your problem, but please read [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – Some programmer dude Jun 11 '19 at 06:54
  • You need `int (*abc)(int,int);` for `abc` to be a *function pointer* of the appropriate type. – Bathsheba Jun 11 '19 at 06:54
  • 1
    More related to your problem, when asking about build errors, always copy-paste (as text) the full and complete error output into the question body. There might be details that you miss if you rewrite just a small part of the message. – Some programmer dude Jun 11 '19 at 06:56
  • `lvalue required as left operand of assignment`. You cannot assign a function to another function – Alejandro Blasco Jun 11 '19 at 06:56
  • 1
    Lastly, in C++ I really recommend you avoid pointers to functions. If you need a callable object use [`std::function`](https://en.cppreference.com/w/cpp/utility/functional/function) instead. – Some programmer dude Jun 11 '19 at 06:57
  • 6
    @Someprogrammerdude, with `std::function` you pay for type erasure, with a function pointer you don't. – Evg Jun 11 '19 at 07:01

1 Answers1

14
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.

Bathsheba
  • 220,365
  • 33
  • 331
  • 451
StoryTeller - Unslander Monica
  • 148,497
  • 21
  • 320
  • 399