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?
}
Short answer: it gets called when the pointers in the array are called. For example:
sample_struct_table[0].foo(...);(Obviously replacing the elipses with the parameters needed to call the function).
Long answer: C can have a pointer to a function, which means that you can load shared object (.dll, .so, etc) and look for functions defined at runtime, then call those functions with out ever linking to them. This is very powerful. If you are creating a struct that contains pointers to your functions, that is really most useful only if you want to call a series of functions using a loop. I suppose if a part of the struct were an int, the functions could specify which function to call next, but I can’t imagine a scenario where this would be useful. If you’re familiar with Scala and have used it in a system, then this shouldn’t be hard to figure out, as Scala does this all the time.
scala> 1 to 10 foreach printlnHere the foreach function accepts a function that accepts a single Int as a parameter. We are passing the println function (def println(x : Any) = …) as a parameter to foreach.