#include#include using namespace std; //How to Replace a Switch-Statement with a founction 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;} /*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; } cout << "Switch: 2+5=" << result << endl; // display result }*/ void Switch_With_Function_Pointer(float a, float b, float (*pt2Func)(float, float)) { float result = pt2Func(a, b); // call using function pointer cout << "Switch replaced by function pointer: 2-5="; // display result cout << result << endl; } // Execute example code void Replace_A_Switch() { cout << endl << "Executing function 'Replace_A_Switch'" << endl; Switch(2, 5, '+'); Switch_With_Function_Pointer(2, 5, /* pointer to function ’Minus’ */ &Plus); Switch_With_Function_Pointer(2, 5, /* pointer to function ’Minus’ */ &Minus); Switch_With_Function_Pointer(2, 5, /* pointer to function ’Minus’ */ &Multiply); Switch_With_Function_Pointer(2, 5, /* pointer to function ’Minus’ */ &Divide); } int main(){ Replace_A_Switch(); int a; cin>>a; return 0; }
Sunday, August 28, 2011
Replace a Switch-Statement by Function Pointer
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment