Reputation: 398
Im reading a book and there is no online code reference so I don't understand couple of things. Complete code:
#include <stdio.h>
/* The API to implement */
struct greet_api {
int (*say_hello)(char *name);
int (*say_goodbye)(void);
};
/* Our implementation of the hello function */
int say_hello_fn(char *name) {
printf("Hello %s\n", name);
return 0;
}
/* Our implementation of the goodbye function */
int say_goodbye_fn(void) {
printf("Goodbye\n");
return 0;
}
/* A struct implementing the API */
struct greet_api greet_api = {
.say_hello = say_hello_fn,
.say_goodbye = say_goodbye_fn
};
/* main() doesn't need to know anything about how the
* say_hello/goodbye works, it just knows that it does */
int main(int argc, char *argv[]) {
greet_api.say_hello(argv[1]);
greet_api.say_goodbye();
printf("%p, %p, %p\n", greet_api.say_hello, say_hello_fn, &say_hello_fn);
exit(0);
}
I have never seen before:
int (*say_hello)(char *name);
int (*say_goodbye)(void);
and:
struct greet_api greet_api = {
.say_hello = say_hello_fn,
.say_goodbye = say_goodbye_fn
};
I kind a understand what is happening there, but as I stated before I have never seen that before.
Those things are double brackets in first snippet. Equal sign, dots and function name w/o brackets in second snippet.
If someone could post some good articles or titles of what is that so I can look online it, I would really appreciate it.
Upvotes: -1
Views: 109
Reputation: 63114
These are respectively function pointers and designated initializers. The function names without brackets are just the way you take a function's address to store it in a function pointer (the &
is facultative in this case).
Upvotes: 3
Reputation: 73366
The first two are function pointers (How do function pointers work) and then, the author initializes these two pointers via the designated initializers (check this answer).
Upvotes: 1