5

My following code is working fine. But I have little doubt, please see //Comment1 and //Comment2

#include<stdio.h>
#include<string.h>

struct PTR
{
    int (*funptr)(int);
};

int fun1(int)
{
    printf("Fun1\n");
    return 0;
}

int fun2(int)
{
    printf("Fun2\n");
    return 0;
}

int main()
{
    PTR p;
    p.funptr = &fun1; //Comment1
    p.funptr(5);

    printf("\n");

    p.funptr = fun2; //Comment2
    p.funptr(5);


  return 0;

}

Output : Fun1 Fun2

There is no problem in output.

At comment1 '&' opertor is used, so we are expllicing telling to get address, in comment2, we are not using '&', so which one is correct way?

Pranit Kothari
  • 9,721
  • 10
  • 61
  • 137

2 Answers2

1

Here,

p.funptr = &fun1 we are giving the address of the function. So '&' here is optional as p.funptr = fun1 also assign address of function.

ajay_t
  • 2,347
  • 7
  • 37
  • 62
1

'&' is optional when taking the address of function。

Zwy
  • 353
  • 1
  • 10