Reputation: 65
I am a bit rusty in programming, so I came here to ask what's the meaning of this line?
int (*f)(int, int)
Upvotes: 1
Views: 4938
Reputation: 12668
int (*f)(int, int)
f
is a pointer to a function that returns an integer and takes two integers as parameters. You can store on that pointer variable (if you prepend that statement with a typedef
particle, then you are defining a pointer to function type, instead) a reference (by using just the function name, withoug the '()' parenthesis) to any function that takes two integers and returns one integer, and later call the function (that could be dynamically assigned to the pointer, so it is posible to change the function called) by using:
int a = (*f)(3, 4);
or the simpler abbreviation:
int a = f(3, 4);
(this will call the actual function for which you have stored its reference in f
)
Upvotes: 0
Reputation: 123458
It declares f
as a pointer to a function taking two int
parameters and returning an int
:
f -- f
(*f) -- is a pointer to
(*f)( ) -- a function taking
(*f)( ) -- unnamed parameter
(*f)(int, ) -- is an int
(*f)(int, ) -- unnamed parameter
(*f)(int, int) -- is an int
int (*f)(int, int) -- returning int
Function pointers typically get used when you're dealing with callbacks (the qsort
library function is probably the canonical example) or when using functions in a shared or dynamically loaded library:
int (*f)(int, int) = dlsym( shared_lib, "foo" );
They're also handy for building table-driven code - I once wrote a utility to load and parse different types of data files from various scientific instruments and load them into a database, each of which had slightly different formats based on the instrument and type of data. So I built a table that was keyed by instrument and data type, with a pointer to the appropriate parsing function:
struct parser_lookup {
char *instrument; // name of the instrument
char *type; // sample data, calibration data, etc.
void (*parser)( const char *fname, db_handle *db );
} parser_table =
{
{ "GRA", "DAT", parse_gra_dat },
{ "GRA", "CAL", parse_gra_cal },
{ "SHR", "DAT", parse_shr_dat },
{ "SHR", "CAL", parse_shr_cal },
...
};
then I had a function to search the table:
void (*get_parser( const char *filename ))(const char *, db_handle * )
{
// Extract instrument and data type from the file name,
// search the table and return the appropriate function pointer
// or NULL
}
then in the main code I had
db_handle *db;
char *fname;
...
while ( (fname = next_file_in_queue()) )
{
void (*parse)(const char *, db_handle *) = get_parser( fname );
if ( parse )
parse( fname, db );
}
That way when a new instrument got added all I had to do was write a new parsing function and add an entry to the lookup table - I didn't have to touch the main application logic.
Upvotes: 4
Reputation: 493
Use https://cdecl.org/ to translate thigs like that.
int (*f)(int, int)
=> declare f as pointer to function (int, int) returning int.
Upvotes: 6