Function pointer array for Command Parsing

Source: Internet
Author: User

Today, I accidentally saw the FTP of huanshen.CodeThe array of function pointers is used for Command Parsing, which saves a lot of strcmp functions. If you think it is very high-end, you just want to record them. At the same time, the freshman in the group is also doing these things, I think you can refer to this method for processing commands. Let's look at a test function you have written. After reading it, you should understand what you have said:

 # include 
  
    # include 
   
     # include 
    
      # include 
     
       char cmd [5] [15] = {"ls", "Search", "Download", "uoload", "update_file "}; void (* do_cmd_func [5]) (const char * command); void fun0 (const char * command) {printf ("this is function0 with command % s \ n ", command);} void fun1 (const char * command) {printf ("this is function1 with command % s \ n", command);} void fun2 (const Char * command) {printf ("this is function2 with command % s \ n", command);} void fun3 (const char * command) {printf ("this is function3 with command % s \ n", command);} void fun4 (const char * command) {printf ("this is function4 with command % s \ n", command);} int main (INT argc, char * argv []) {int I; dependencies [0] = fun0; do_cmd_func [1] = fun1; do_cmd_func [2] = fun2; do_cmd_func [3] = fun3; do_cmd_func [4] = fun4; printf ("init over! Start do_1__func: \ n "); for (I = 0; I <5; I ++) {do_1__func [I] (CMD [I]);} printf ("Point function_set has done! \ N "); Return exit_success ;}
     
    
   
  

Initialize a command character array in the code, and then store the corresponding call function in the corresponding position in the function pointer array. Finally, we make things for ourselves, when we determine the command, we only need one sentence. (Note: char * CMD is the received command string, tip is the value of the function that corresponds to the function pointer array .)

 
Do_cmd_func [tip] (CMD );

This is a good design concept.

 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.