My notes on Function Pointers in C

Function code is stored in the memory, start of the function code or address of a function is a "function pointer"

1. Function Pointers point to the code, not data
2. Function pointer is different from normal pointer, Function name can be used to get the function address
Syntax: return_type (*pointer_name)(argument_list)
Note: Remember always the declaration name is preceded by * and enclosed in parenthesis (), If we remove the bracket the meaning changes.
E.g.
void display(int a)
{
           printf("value of a is %d\n", a);
}

int main()
{
     void (*func)(int) = display;
      func(10);
      return 0;
}

3. Like normal pointers, we can have arrays of function pointers.

void add(int a, int b)
{
       printf("a+b:%d\n", a+b);
}
void subtract(int a, int b)
{
       printf("a-b:%d\n", a-b);
}
void mul(int a, int b)
{
       printf("a*b:%d\n", a*b);
}
void div(int a, int b)
{
       printf("a/b:%d\n", a/b);
}

int main()
{
       void (*func[])(int, int) = {add, subtract, mul, div};
       (*func[0])(3,3);
       (func[1])(2,4);
}

4. Function Pointer can also be passed as an argument to the function

void print1(void)
{
     printf("hello\n");
}

void print2(void)
{
     printf("bye\n");
}
   
void print(void (*func)())
{
        func();
}

int main()
{
      print(print1);
      print(print2);
}

Using typedef on Function Pointers:

It is often convenient to use a typedef to define the function type.

E.g. typedef void (*fnptr)(int);

Now, you have defined a type fnptr. Variables of this type can point to functions that take int as an argument and return void

E.g fnptr v;

Use of function pointers:

Setting up callback functions or listener functions, that are invoked when a particular event happens.  For example, button callback when user clicks on button.

Declaring function pointers inside struct:

struct abc {
      int a;
      int b;
      int c;
      int (*add)(int a, int b);
      int (*subtract)(int a, int b);
      int (*divide)(int a, int b);
      int (*multiply)(int a, int b);
};


Comments

Popular posts from this blog

bb.utils.contains yocto

make config vs oldconfig vs defconfig vs menuconfig vs savedefconfig

PR, PN and PV Variable in Yocto