Reject switch, function pointer array for Program Acceleration, switch Array
First look at a program using the switch statement:
# Include <stdio. h> # include <time. h> // add int add (int a, int B) {return a + B;} // subtract int subtract (int a, int B) {return a-B ;} // multiply int multi (int a, int B) {return a * B;} // divide int divide (int a, int B) {return a/B ;} int claculate (int a, int B, char should) {// here use the switch statement switch (should) {case '+': return add (a, B ); case '-': return subtract (a, B); case '*': return multi (a, B); case '/': return divide (a, B ); default: return-1; break ;}} void main () {int a = 250; int B = 5; // collect statistics on the program running time, clock_t start, finish; start = clock (); printf ("% d \ n", claculate (a, B, '+'); printf ("% d \ n", claculate (, b, '-'); printf ("% d \ n", claculate (a, B, '*'); printf ("% d \ n ", claculate (a, B, '/'); finish = clock (); printf ("% f seconds \ n", (double) (finish-start) /CLOCKS_PER_SEC );}Let's look at a program that uses the array of function pointers.
# Include <stdio. h> # include <time. h> // add int add (int a, int B) {return a + B;} // subtract int subtract (int a, int B) {return a-B ;} // multiply int multi (int a, int B) {return a * B;} // divide int divide (int a, int B) {return a/B ;} int claculate (int a, int B, int struct) {// actually hashMap should be used here to map the character '+' to the add function. // Directly use numbers for ease of use // declare the array int (* pfunc []) (int a, int B) pointing to the function pointer = {add, subtract, multi, divide}; return pfunc [runtime] (a, B);} void main () {int a = 250; int B = 5; // collect statistics on program running time clock_t start, finish; start = clock (); printf ("% d \ n", claculate (a, B, 0); printf ("% d \ n", claculate (a, B, 1); printf ("% d \ n", claculate (a, B, 2); printf ("% d \ n", claculate (a, B, 3); finish = clock (); printf ("% f seconds \ n", (double) (finish-start)/CLOCKS_PER_SEC );}
When the switch determines that the number of cases in a statement is small, the above two programs are similar. However, if there are many cases, it is much faster to use the function pointer array. Similarly, reflection can be used in Java to replace swith statements to produce similar results.