0

I get little confused with pointer to function.

Let’s say

int func (int parameter){
    return parameter + 5;
}
int (* pfunction)(int) = func;

pfunction(5); //this will return 10

But I wonder what it means without parantheses. Like this.

pfunction

*pfunction

I know the difference between these two in case of pointer to int, float, double ... but I have no clue what these two mean when it comes to pointer to function.

Could you explain this?

hoo
  • 67
  • 4
  • 3
    "what it means without parentheses." --> post how you might use this in code. `pfunction` , `*pfunction` by themselves means little. – chux - Reinstate Monica Feb 17 '21 at 15:34
  • An `int` is just a value, stored in memory. An `int*` is a pointer to that piece of memory. A function pointer is a pointer to where a function in the memory starts (where the machine code of that function begins). The function itself is the ordered set of instructions. – Captain Trojan Feb 17 '21 at 15:37
  • The TL;DR is that the forms are equivalent when it comes to functions, since a function identifier always "decays" into a function pointer when used in an expression. For details check the linked duplicate. – Lundin Feb 17 '21 at 15:49

1 Answers1

2

pfunction means function pointer and it holds the reference to the function

*pfunction dereferenced function pointer will give the same reference to the function

&pfunction address of the pfunction pointer

when calling function pointers both forms are correct: pfunction(5) and (*pfunction)(5)

Example:

int  func (int parameter){
    return parameter + 5;
}
int main(void)
{
    int (*pfunction)(int) = func;

    printf("%d\n", pfunction(5)); //this will return 10
    printf("%d\n", (*pfunction)(5)); //this will return 10

    printf("pfunction \t%p\n", (void *)pfunction);
    printf("*pfunction \t%p\n", (void *)*pfunction);
    printf("&pfunction \t%p\n", (void *)&pfunction);
    printf("%p\n", (void *)func);
    printf("%p\n", (void *)main);
}

https://godbolt.org/z/7eq581

0___________
  • 60,014
  • 4
  • 34
  • 74