What exactly is the difference between these two pointers if both are pointing to a function. The truth is that I have seen many programmers using them but I still do not see the difference.
int(*function)(int,int)
and
int*function(int,int)
What exactly is the difference between these two pointers if both are pointing to a function. The truth is that I have seen many programmers using them but I still do not see the difference.
int(*function)(int,int)
and
int*function(int,int)
This is a function pointer:
int(*function)(int,int)
Used to dynamically target a function:
int func1(int a, int b)
{ return a + b; }
int func2(int a, int b)
{ return a * b; }
int main()
{
int (*funcion)(int,int) = func1;
printf("%d\n",funcion(2,4)); // Imprime 6 (2 + 4)
funcion = func2;
printf("%d\n",funcion(2,4)); // Imprime 8 (2 * 4)
}
And this other is a function that returns a pointer of type int
:
int* function(int,int)
As for example:
int* funcion(int a, int b)
{
static int total= 0;
total= a + b;
return &total;
}
int main()
{
int* resultado = funcion(1,2);
printf("%d\n",*resultado); // Imprime 3
funcion(2,4);
printf("%d\n",*resultado); // Imprime 6
}
The second result is explained because resultado
points to the internal variable of the function, total
. Being this static variable every time the function is called, the value stored in it will be modified.
Parentheses are very important in C, so you have to put them very carefully if you do not want the program to start doing weird things.
The first int(*function)(int,int)
is a function pointer. Parentheses ()
have priority. I recommend you to see the priority of operators in C, here I leave a link link
The second is a function that returns a pointer to int