0

I am curious how C handle the function name. To be specific, is the function name a pointer to the beginning address of the function body, like array name is? If that is the case, when assign a value to function pointer, why people sometimes apply reference & to the function name like:

int foo(int a, int b);
int (*p_func)(int a, int b) = &foo;

I know that we can directly assign foo to p_func without reference. But it underlying does implicit conversion to retrieve the function pointer and then assign to p_func. So seems like there is difference between function name and function pointer. Then what is it?

Thank you!

AntonH
  • 6,359
  • 2
  • 30
  • 40
Alfred
  • 1,709
  • 8
  • 23
  • 38
  • 2
    There is no difference. The standard says that `foo` is the same as `&foo` in that context. – Jon May 13 '14 at 22:16
  • 1
    There is no such thing as reference in C. – Chnossos May 13 '14 at 22:17
  • Neither an array name nor a function name is a pointer. An expression of array or pointer type (including the name of an array object or of a pointer) is implicitly *converted* to a pointer (to the array's first element or to the pointer, respectively) in most but not all contexts. – Keith Thompson May 13 '14 at 22:20
  • @KeithThompson: And an expression that is an id-expression that names a function decays to a pointer to that function in most (but not all) cases... – Kerrek SB May 13 '14 at 22:36
  • @KeithThompson so in what context, function name is different from the pointer to the function? – Alfred May 13 '14 at 22:47
  • @KerrekSB: What is an "id-expression"? And yes, I meant to say "(to the array's first element or to the function, respectively)". – Keith Thompson May 13 '14 at 23:07
  • @Guoqin: If `func` is a function name and `ptr` is a function pointer, `sizeof ptr` yields the size of the pointer, but `sizeof func` is illegal. Also, `&func` yields a pointer to the function, but `&ptr` yields a pointer to the pointer object. – Keith Thompson May 13 '14 at 23:09
  • @KeithThompson: It's just the term for an expression that just consists of an identifier, like `foo` in the OP's code. – Kerrek SB May 14 '14 at 07:46
  • @KerrekSB: The C standard doesn't use the term *id-expression*, and the rule applies to *any* expression of function type (such as `*func_ptr`). – Keith Thompson May 14 '14 at 14:48
  • @KeithThompson: Ah, indeed, good point. – Kerrek SB May 14 '14 at 20:56

0 Answers0