-1

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.

1
  • There is no online reference for C?? Commented Nov 1, 2014 at 23:55

2 Answers 2

3

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Aren't designated initializers a GNU C extension?
1

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).

2 Comments

Not a dot operator :)
Well thank you ! I had a bit of trouble formatting the links :p

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.