views:

118

answers:

2

Hi,

Check the below code

int add(int a, int b)
{
    return a + b;
}

void functionptrdemo()
{
    typedef int *(funcPtr) (int,int);
    funcPtr ptr;
    ptr = add; //IS THIS CORRECT?
    int p = (*ptr)(2,3);
    cout<<"Addition value is "<<p<<endl;
}

In the place where I try to assign a function to function ptr with same function signature, it shows a compilation error as error C2659: '=' : function as left operand

+8  A: 

It is very likely that what you intended to write was not:

typedef int *(funcPtr) (int,int);

but:

typedef int (*funcPtr) (int,int);
Alexandros Gezerlis
Answer is perfect. Thanks
AKN
@KN: If the answer is perfect, you should accept it.
sbi
@sbi: I tried it immediately. But the site didn't allow me to accept the answer with in 5 minutes :)
AKN
@AKN: I'm sorry I was so impatient. `:)`
sbi
+2  A: 

Alex answer is correct. But the good practice will be

ptr = &add;

if you write like this below:

ptr = add;

it is the compiler which assumes that you wanted to store the address of the function add. So better let's not make the compiler to assume.

Vijay Sarathi
there is no assumption functions can only be stored as pointers
jk
jamesdlin