1

I'm trying to figure out the following code. Especially the part that relates to the function typedef.

#include <stdio.h>
void foo1(int var1, int var2); // foo1 decleration
typedef void (foo2)(int var1, int var2); // what is this exactly?

typedef struct somestruct{
    foo2* somefunc;
}SOMESTRUCT;

int main()
{
    SOMESTRUCT struct1;
    struct1.somefunc = &foo1; 
    struct1.somefunc(1,5);
    return 0;
}

void foo1(int var1, int var2){
    printf("this is function inside struct var1 = %d var2 = %d",var1, var2);
}
  • typedef creates a type SOMESTRUCT. You declare an instance struct1. You set the function in struct1 and then call it. – stark Nov 07 '18 at 16:01
  • The answer beneith this post might help https://stackoverflow.com/questions/1591361/understanding-typedefs-for-function-pointers-in-c – Yastanub Nov 07 '18 at 16:06

2 Answers2

1

The line...

typedef void (foo2)(int var1, int var2); // what is this exactly?

...declares a new type, foo2, as a function that takes two int parameters and returns void.

Later in the code, the address of function foo1 (which matches the function signature) is stored in the somefunc member of struct1, and then it's called. with parameters 1 and 5.

Tim Randall
  • 4,040
  • 1
  • 17
  • 39
0

Tim Randall's explanation is pretty good but let me add this.

The typedef keyword defines a new data type that can be used in place of its original definitions. If you did not want to use typedef, the structure could have been defined as:

typedef struct somestruct{
    void(*somefunc)(int a,int b);
}SOMESTRUCT;

In this case, we don't save much but if we had more than one function pointer, the use of the typedef saves quite a bit and makes the program easier to read.

user1683793
  • 1,213
  • 13
  • 18