Home > Net >  Referencing a function pointer with ampersand works fine while I prefer without but using & is an in
Referencing a function pointer with ampersand works fine while I prefer without but using & is an in

Time:09-22

The code below shows the reference to function pointer:

typedef int (*t_somefunc)(int,int);
int product(int, int);
int main(void) {
  t_somefunc afunc = &product; // "product" works fine without "&"

What do we use "&" for referencing function pointer?
See full working code:

#include <stdio.h>
typedef int (*t_somefunc)(int,int);
int product(int, int);

int main(void) {
  t_somefunc afunc = &product; // product without & works also
  int x2 = (*afunc)(123, 456); // call product() to calculate 123*456
  printf("x2 value is %d\n", x2);
  return 1;
}

int product(int u, int v) {
  return u*v;
}

CodePudding user response:

Functions are automatically converted to pointers for programmer convenience.

When a function is used in an expression, it is automatically converted to a pointer to the function, unless it is the operand of sizeof or unary &. C 2018 6.3.2.1 4 says:

A function designator is an expression that has function type. Except when it is the operand of the sizeof operator, or the unary & operator, a function designator with type “function returning type” is converted to an expression that has type “pointer to function returning type”.

(In fact, if you attempt to convert the pointer back to a function by applying *, the automatic conversion will happen again. You can write t_somefunc afunc = *******************product; and still end up with the address of product.)

In declarations of function parameters, a function will be automatically adjusted to be a pointer to a function. C 2018 6.7.6.3 8 says:

A declaration of a parameter as “function returning type” shall be adjusted to “pointer to function returning type”, as in 6.3.2.1.

(This is called an adjustment because there is no value being converted; the declaration is changed to declare a pointer to a function instead of a function.)

  • Related