user611469
user611469

Reputation: 13

calling a function from a structure

i have the following code. I just want to know the meaning of the last line of the code.

typedef struct Details 
{
int D1; 
int D2;
} Sdetails;




typedef struct  Variable    
{
    int   Type; 
    Sdetails  i;
}Varialbl3;


typedef XAN_BOOL (*returnfunction)(variabl3* Data);


typedef struct _function
{
    returnfunction          fr;

}function1;


function1 *f1;
variabl3  v3;

f1->fr(&v3);

what does the last line f1->fr(&v3) indicates? I dont understand the concept.

Upvotes: 0

Views: 485

Answers (4)

Bruce
Bruce

Reputation: 7132

It's a pointer on a function : basically, you're calling an abstract function that can be set somewhere else.

You should have a real function somewhere like:

XAN_BOOL realFunction(variabl3* pxData) { return (pxData==0); }

Then you can do : f1->fr = realFunction : you make your function pointer point to the real function. Then, when you call f1->fr after, it will call realFunction.

This is widely used in a lot of design patterns : when you want to register callbacks, in listeners/triggers, when you want to implement object-oriented design in pure C, when you want to eract to UI (you attach a behaviour to a button, in GTK for example).

Hope this helps, if anything unclear, ask in comment and I'll edit.

Upvotes: 0

Kiril Kirov
Kiril Kirov

Reputation: 38143

It calls fr function.

f1 is pointer to function1 (which is struct):

typedef struct _function
{
    returnfunction          fr;
}function1;

function1 has member - a pointer to function - named fr. The function, pointer by fr takes one argument - variabl3:

// pointer to function, taking one argument with type 
// `variabl3` and returns typedef struct _function
typedef XAN_BOOL (*returnfunction)(variabl3* Data);

So, f1->fr(&v3) calls fr and passes v3 as parameter. The return value is XAN_BOOL, as described in the typedef.


By the way, if this is real code - this is undefined behaviour as f1 is uninitialized.

Upvotes: 2

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81674

f1 is a pointer a kind of struct; that struct's only member is a pointer to a function. That last line calls the function held by the pointer in an instance of that struct, and passes the address of an instance of the variable3 struct as the function's argument.

Upvotes: 1

NPE
NPE

Reputation: 500167

f1 is a pointer to a struct. The struct has a member called fr, which is a pointer to a function. The function takes a pointer to variabl3 and returns XAN_BOOL.

Thus, f1->fr(&v3) calls the function pointed to by f1->fr, supplying the address of v3 as the sole argument, and ignoring the return value.

Upvotes: 4

Related Questions