/* This program was originally written in C++ i */ /* hopefully this is properly translated into C */ /* from: http://www.newty.de/fpt/intro.html */ /*------------------------------------------------------------------------------------ */ /* 1.2 Introductory Example or How to Replace a Switch-Statement */ /* Task: Perform one of the four basic arithmetic operations specified by the */ /* characters '+', '-', '*' or '/'. */ #include /* The four arithmetic operations ... one of these functions is selected */ /* at runtime with a switch or a function pointer */ float Plus (float a, float b) { return a+b; } float Minus (float a, float b) { return a-b; } float Multiply(float a, float b) { return a*b; } float Divide (float a, float b) { return a/b; } /* Solution with a switch-statement - specifies which operation to execute */ void Switch(float a, float b, char opCode) { float result; /* execute operation */ switch(opCode) { case '+' : result = Plus (a, b); break; case '-' : result = Minus (a, b); break; case '*' : result = Multiply (a, b); break; case '/' : result = Divide (a, b); break; } printf ("Switch: 2+5= %f\n", result); } /* Solution with a function pointer - is a function pointer and points to */ /* a function which takes two floats and returns a float. The function pointer */ /* "specifies" which operation shall be executed. */ void Switch_With_Function_Pointer(float a, float b, float (*pt2Func)(float, float)) { float result = pt2Func(a, b); /* call using function pointer */ printf ("Switch replaced by function pointer: 2-5= %f\n", result); } /* Execute example code */ int main () { /* for third parameter: '+' specifies function 'Plus' to be executed */ Switch(2, 5, '+'); /* for third parameter: pointer to function 'Minus' */ Switch_With_Function_Pointer(2, 5, Minus); }