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.,?