-1

I want to pass a function as parameter, but I am confused if I should pass it with ampersand or not. The following snippet works in both ways. Why?

#include <stdio.h>

int print(int pas){
return pas;
}


int func_print(int (*k)(int)){
(*k)(555);
}

int main(){



printf("%d",func_print(print));
printf("%d",func_print(&print));

return 0;
}
loannnlo
  • 111
  • 1
  • 6

1 Answers1

1

Function names are special.

When used without calling the function, it automatically is translated to a pointer to the function. So &print, print, *print, **print, ***print, etc. all evaluate to the same expression of type int (*)(int).

dbush
  • 205,898
  • 23
  • 218
  • 273
  • In fact, a function identifier is converted to a pointer to the function *wherever* it appears in a valid expression, except as the operand of the address-of, `sizeof`, or `_Alignof` operators (C11 6.3.2.1/4). In particular, this is the only type family allowed for the operand of a function call expression: "The expression that denotes the called function shall have type pointer to function [...]" (C11 6.5.2.2/1). This is closely analogous to arrays decaying to pointers. – John Bollinger Aug 22 '18 at 15:03