Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is a struct initialized in C?

Tags:

c

I am new to C, from a Java background.

If I have a struct that is initialized on the fly with data that comes from functions inside of the struct definition, when do those functions get called? When does this code run? Is it just on the first reference to sample_struct_table[i]?

static struct sample_struct {
    int         command;
    int         (*foo)( obj1 *banana, int num);
} sample_struct_table[] = {
    {   .command    =   COMMAND_1,
        .foo =   function_name,
    },
    {   .command    =   COMMAND_2,
        .foo =   another_function_name,
    },
};

static int function_name(obj1 *banana, int num)
{
      // do stuff here
      // When does this get called?
}
like image 770
boltup_im_coding Avatar asked Jan 23 '26 10:01

boltup_im_coding


1 Answers

The functions get called when you call them. In your example, all you are doing is setting the field of the structure to the function pointer. The function is not called, you just have a pointer pointing to it.

like image 93
RonaldBarzell Avatar answered Jan 25 '26 17:01

RonaldBarzell