The advantage of function pointers over flags

Say, for example, I have a function called int compute (int x1, int x2, int (* op) (int, int)) , which takes as an argument a pointer to a function for a function that performs some arithmetic operation

int add (int a1, int a2) { return (a1 + a2); } int mul (int s1, int s2) { return (s1 * s2); } int compute (int x1, int x2, int (* op) (int, int) ) { return ( op (x1, x2) ); } main() { int result; int op1, op2; op1 = 4; op2 = 5; result = compute (op1, op2, &add()); result = compute (op1, op2, &mul()); } 

Instead of all this element of a function pointer, I can also use flags as an argument, rather than a function pointer, to achieve the same.

 int compute (int x1, int x2, int opFlag) { if ( opFlag == 1 ) return ( add (x1, x2); ); if ( opFlag == 2) return ( mul (x1, x2); ); return 1; } main() { int result; int op1, int op2; op1 = 4; op2 = 5; result = compute (op1, op2, 1); result = compute (op1, op2, 2); } 

Now the question is, what are the advantages (ad / disad) of the "simple flag" approach function pointer in terms of efficiency, code size, portability, readability, etc.,?

+4
source share
2 answers

what are the advantages (ad / disad) of the function pointer approach to the simple flag approach in terms of efficiency,

Fewer calls can be faster. On many processors, function calls have a significant cost when you make a lot of them.

code size

Fewer functions may be less, since you do not have duplicated overheads of the function prolog and epilog code.

tolerance

It does not apply as long as your code is correct, it does not suffer from undefined behavior and does not depend on implementation-specific behavior.

readability

May be subjective. Often, fewer layers of abstraction and less guidance are easier to understand than more.

etc.,?

Define etc

+1
source

how about when you want to add a new operation?

Function pointers allow you (or your future clients of your libraries) to do this without changing the calculation function

0
source

All Articles