David Smith
David Smith

Reputation: 187

Explain the following code?

There are several things I don't understand about the below snippet of code (written in C):

struct T {
int a;
int *b;
struct T *next;
} ;

struct T *p1;

struct T* (*f)(int, int, struct T*);

struct T* g(int a, int b, struct T* c)
{
    return (a > b ? c : NULL);
}

f = &g;
p1 = (*f)(4,3,p1);

In particular, what does this line mean?

struct T* (*f)(int, int, struct T*);

Is this a function? If so, why doesn't it have a body, and why are there formal parameter names that appear to be missing? What does this function return, if it lacks a body?

Also, what is going on with the assignment below?

f = &g;

Upvotes: 2

Views: 223

Answers (4)

Chrisky
Chrisky

Reputation: 567

So f is a pointer to a function, which takes int, int, struc T * and returns a struct T *. f is assigned to the address of g, which is a common-or-garden function. Then that line with p1 is invoking f(), which actually invokes g().

BTW, I can seriously recommend Peter van der Linden's book "Deep C Secrets" - very readable, and now released as pdf.

Upvotes: 2

Mahonri Moriancumer
Mahonri Moriancumer

Reputation: 96

In particular, what does this line mean?

struct T* (f)(int, int, struct T);

declares f as a pointer to a function which takes the parameters (int, int, struct T*) and which returns a pointer to a struct T.

Is this a function?

No. However, f can point to a function.

why doesn't it have a body?

As a pointer to a function, it only requires sufficient definition to let the compiler know the prototype of the function it will point to. In this case, it ends up pointing to the function g; and so it's prototype should match g's definition (or a warning will result).

why are there formal parameter names that appear to be missing

Names of the arguments are optional for function pointers. Only the argument types are needed.

Also, what is going on with the assignment below?

f = &g;

(function) pointer f is assigned the address of (function) g.

And finally...

p1 = (*f)(4,3,p1);

The function pointed to by f (ie: g) is called with the values(4,3,p1). The value returned is placed into p1.

Upvotes: 3

ArtemB
ArtemB

Reputation: 3622

You are looking at a function pointer variable. Here's how to parse them:

struct T* (*f)(int, int, struct T*);

f is a pointer

struct T* (*f) (int, int, struct T*);

..to a function that takes two int arguments and one pointer to struct T

struct T* (*f)(int, int, struct T*);

.. and returns a pointer to struct T

Now that you know that f is a function pointer variable, the meaning of f = &g; should be obvious.

Hint: g is a function.

Upvotes: 1

twid
twid

Reputation: 6686

Line struct T* (*f)(int, int, struct T*);, Is function pointer, Where you define pointer to function, Which takes three arguments (int, int, struct T*).

And Code f = &g; means you are assigning function pointer f with function g.

Upvotes: 5

Related Questions