c - Why are function pointers useful? -
so, looking on function pointers, , in examples have seen, particularly in answer here. seem rather redundant.
for example, if have code:
int addint(int n, int m) { return n+m; } int (*functionptr)(int,int); functionptr = &addint; int sum = (*functionptr)(2, 3); // sum == 5
it seems here creating of function pointer has no purpose, wouldn't easier this?
int sum = addint(2, 3); // sum == 5
if so, why need use them, purpose serve? (and why need pass function pointers other functions)
simple examples of pointers seem useless. it's when start doing more complicated things helps. example:
// elsewhere in code, there's sum_without_safety function blindly // adds 2 numbers, , sum_with_safety function validates // numbers before adding them. int (*sum_function)(int, int); if(needs_safety) { sum_function = sum_with_safety; } else { sum_function = sum_without_safety; } int sum = sum_function(2, 3);
or:
// array of functions. we'll choose 1 call based on // value of index. int (*sum_functions)(int, int)[] = { ...a bunch of different sum functions... }; int (*sum_function)(int, int) = sum_functions[index]; int sum = sum_function(2, 3);
or:
// poor man's object system. each number struct carries table of // function pointers various operations; can appropriate // function , call it, allowing sum number without worrying // how number stored in memory. struct number { struct { int (*sum)(struct number *, int); int (*product)(struct number *, int); ... } * methods; void * data; }; struct number * num = get_number(); int sum = num->methods->sum(number, 3);
the last example how c++ virtual member functions. replace methods struct hash table , have objective-c's method dispatch. variable pointers, function pointers let abstract things in valuable ways can make code more compact , flexible. power, though, isn't apparent simplest examples.
Comments
Post a Comment